0


How can I use str_replace in PHP without allowing it to re-replace the characters that have been used in the $replace_with in the following code?

<?php
 $string='abcd';
 $replace= array('a','c');
 $replace_with = '[ac]';
 $string=str_replace($replace,$replace_with,$string);
 echo $string;
?>

The result would be:
"[a[ac]]b[ac]d"
How can I force my script to replace the 'a' in $string with '[ac]' once only without allowing it to replace the 'c' inside the newly inserted '[ac]'?

Cecel
  • 27
  • 1
  • 5

1 Answers1

1

strtr() does precisely what you ask:

$string = strtr( $string, array( 'a'=>'[ac]', 'c'=>'[ac]' ) );

Output:

[ac]b[ac]d

Relevant excerpt:

If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77