1
$replaces = array('replace 1', 'replace thing 2', 'third replace');

$string = '{REPLACEME} sfsfsdfsdf {REPLACEME} sdfopjsd {REPLACEME} sdfsdf {REPLACEME}';

What is the easiest way to replace each successive {REPLACEME} with the matching replace?

If there are more {REPLACEME} than replaces, it should not touch the extra {REPLACEME}'s.

So the output I would want with my example is:

replace 1 sfsfsdfsdf replace thing 2 sdfopjsd third replace sdfsdf {REPLACEME}

3 Answers 3

8
foreach($replaces as $rep) {
  $string = preg_replace('~\{REPLACEME\}~',$rep,$string,1);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Note that with every iteration of the foreach the whole string is searched for {REPLACEME}. If your replacement does also contain that string it gets replaced.
The replacement string is corrupted if it includes a backslash. According to the PHP manual, "To use backslash in replacement, it must be doubled". Therefore, in the example $string in the above should be str_replace ('\\', '\\\\', $string)
2

this might be a quick idea:

$replaces = array('replace 1', 'replace thing 2', 'third replace');
$string = '{REPLACEME} sfsfsdfsdf {REPLACEME} sdfopjsd {REPLACEME} sdfsdf {REPLACEME}';
$sampler = explode('{REPLACEME}',$string);
foreach($sampler as $k=>$v){
 if(isset($replaces[$k])) {
     $sampler[$k] .= $replaces[$k]
 } else {
  $sampler[$k] = '{REPLACEME}' //or whatever
 }
}
$final = implode("",$sampler);
//it's ok for not so long strings or at least not to many {REPLACEME}

Comments

1

Similar to Catalin Marin’s proposal but without the need to check whether there are enough replacement strings:

$parts = explode('{REPLACEME}', $string, count($replaces)+1);
for ($i=0, $n=count($parts); $i<$n; $i++) {
    $parts[$i] .= $replaces[$i];
}
$string = implode('', $parts);

If you need a regular expression for the search, you can use preg_split instead of explode.

The advantages of this solution in opposite to calling str_replace/preg_replace multiple times consecutively are:

  • $string is only searched once for occurrences of {REPLACEME} (only count($replaces) at most)
  • {REPLACEME} does not get replaced if it appears in a previous replacement of $replaces.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.