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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.