Jump to content

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


Go to solution Solved by kicken,

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!

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.