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?

Along with my other suggestion, if you're really looking to replace one
string with another, instead of a regular expression pattern, then you could
use this code, also:

<?php

//Original String
$str = 'bb a a a a a a a a a a bb';
//Search String
$search_string = 'a';
//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,6);

//Explode original string by search string
$ar = explode($search_string,$str);

//Get count of elements. Subtract one since you
//do not to loop through last element
$c = count($ar) - 1;

//Holder for new string
$new_str = '';

//Loop from zero to number of matches minus one ($c).
for($x=0;$x<$c;$x++)
{
    //Add current element to new string
    $new_str .= $ar[$x];

    //if current count is in $instance array, add replacement string
    //otherwise add back original search string
    if(in_array($x+1,$instance))
    { $new_str .= $replacement_string; }
    else
    { $new_str .= $search_string; }
}
//add on final element of array
$new_str .= $ar[$x];

//Display results
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