Jump to content

str_replace - how to skip certain search/replace rules?


amedhussaini

Recommended Posts

I have a STRING full of text ($a)

 

    $search  = array('one', 'two');

    $replace = array('two', 'one');

   

    $a = str_replace($search, $replace, $a);

 

I want to replace 'one' with 'two' in a string if it exists, but i don't want it to revert back to 'two' as it traverses the next bit of the array.  Does this make sense?

 

cheers,

Amed

hrm.. this still seems to change my replacement right back as it traverses the array.  i must be missing something fundamental:

 

    $search  = array('/one/', '/1/');

    $replace = array('1', 'one');     

   

    $a = preg_replace($search, $replace, $a);

 

Just to reiterate, i want it to search through the $string and replace the 'one' it finds with '1' or change any '1' it finds to 'one' the FIRST time it searches through the string.

 

so i'd like the string to transform from:

 

i like one 1 one

 

////after replacement////

 

i like 1 one 1

The only way I can think of doing what you want to do with a "double reverse" (for lack of a better term) in a string is by exploding the string into an array, making an array keyed to the changes then using array_walk to return a referenced array with the changes and imploding that array back to a string. Sounds like a lot but its only a small function and a few more lines of code.

 

function swap($value,$key,&$s)
{
$k=array('1'=>'one','one'=>'1');
$s[]= $k[$value];
}

$a='1 one 1 one';
$aa=explode(" ",$a);
array_walk($aa,swap,&$s);
$ss=implode(" ",$s);
echo $ss;

 

 

HTH

Teamatomic

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.