faqts : Computers : Programming : Languages : PHP : Common Problems : Regular Expressions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

0 of 2 people (0%) answered Yes
Recently 0 of 2 people (0%) answered Yes

Entry

How can I change only the first occurence of a string in a text?

Apr 2nd, 2005 02:19
Michael Zischeck, Kenn E. Thompson, this is almost already answered


Take a look a this answer:

http://www.faqts.com/knowledge_base/view.phtml/aid/7277/fid/7

There you will find the function:

preg_replace_callback( $pattern, "function_name", $text_to_search);

which uses a callback function. Use that function to stop a the entry you want to replace:

function function_name($matches) {
        static $i = 0;
        $stopAtNthOccurrence = 1;
        $i++;
        if( $i == $stopAtNthOccurrence )
        {
             return "replaced text";
        }
        else
        {
             return $matches[0];
        }
}