Jump to content

String search/replace but don't replace things that were already replaced


LLLLLLL

Recommended Posts

The situation is that I have a large string with some identifiers to say "replace me" with something else. My goal is to replace the values, but if one replacement includes one of the other keys, I don't want to replace it.

 

For example:

<?php
$str = 'some blob ~abc~ followed by ~def~';

$arr_orig = array(
	'~abc~',
	'~def~'
);

$arr_new  = array(
	'value~def~',
	'blah'
);

echo str_replace( $arr_orig, $arr_new, $str );
?>

This will echo:

some blob valueblah followed by blah

 

But that's not what I'm trying to accomplish. Basically, I want ~abc~ to be replaced with the literal: value~def~ and for the ~def~ that happens to be part of that string to NOT be replaced. I hope what I'm asking is clear. Basically, preg_replace/str_replace with arrays seems no different than just doing a FOR loop and replacing ~abc~ and then ~def~. But that's not what I need.

 

I'm hoping that if ~abc~ is replaced with text that happens to be another identifier -- ~def~, ~xyz~, whatever -- that this already replaced text is not again replaced. Is there a built-in function to do something like this? If not, should I just parse the whole string and count characters or something? Seems like a pain (and slow!)

Well that's exactly what I wanted. No way I would have known that on my own, although the documentation does state exactly what I wanted: Once a substring has been replaced, its new value will not be searched again.

 

Thanks!

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.