From: "Thaddeus J. Quintin" <[EMAIL PROTECTED]>

> I'm looking to replace the 'nth' instance of an expression within a
string.
>
> Example (very simple)-
>
> $string="My mom can beat up your mom and your mom's dog";
> $pattern="mom";
> $replacement="dad";
>
> I want to be able to replace any particular instance of the pattern
> within that string.  I was getting ready to do it in a very complex
> manner by finding all the matches, splitting on the pattern, and then
> breaking the string down and reassembling it in the proper order.  It
> seems like there might be an easier way to perform this though.
>
> Anyone have any suggestions?

Probably lots of way to do this... here's my suggestion:

<?php

//Original String
$str = 'a b c d a b c d a b c d a b c d a b c d';
//Replacement String
$replacement_string = "ff";

//Instances of search string you want replaced
//i.e. 2nd and 4th instance is array(2,4)
$instance = array(2,4);

//Callback function that manages replacements
function callback($matches)
{
    //Global and static variables. $match_count is
    //static to keep track of what match were currently
    //operating on
    global $replacement_string;
    global $instance;
    static $match_count = 1;

    //determine if current count is in $instance array.
    //if it is, set return value to replacement string,
    //otherwise return matched value unchanged
    if(in_array($match_count,$instance))
    { $retval = $replacement_string; }
    else
    { $retval = $matches[0]; }

    //increment match count
    $match_count++;

    //return replacement string
    return $retval;
}

//replace all 'a' characters with $replacement_str (simple example)
$new_str = preg_replace_callback('/a/','callback',$str);

echo $str . '<hr>' . $new_str;

?>

---John Holmes...


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to