LLLLLLL Posted August 17, 2014 Share Posted August 17, 2014 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!) Link to comment https://forums.phpfreaks.com/topic/290488-string-searchreplace-but-dont-replace-things-that-were-already-replaced/ Share on other sites More sharing options...
kicken Posted August 17, 2014 Share Posted August 17, 2014 strtr Link to comment https://forums.phpfreaks.com/topic/290488-string-searchreplace-but-dont-replace-things-that-were-already-replaced/#findComment-1487991 Share on other sites More sharing options...
LLLLLLL Posted August 17, 2014 Author Share Posted August 17, 2014 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! Link to comment https://forums.phpfreaks.com/topic/290488-string-searchreplace-but-dont-replace-things-that-were-already-replaced/#findComment-1488005 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.