0

Trying to search and replace some content using str_replace(). It works fine if the $find is unique, but once if $find has duplicate words, the whole thing messed up.

e.g. The style1 will be applying on both $find[0] && $find[1] since both are Lorem Ipsum, same goes for dummy.

How to deal with this situation?

$find = Array(
    [0] => Lorem Ipsum 
    [1] => Lorem Ipsum 
    [2] => typesetting 
    [3] => dummy 
    [4] => dummy 
);

$replace = Array(
    [0] => style1
    [1] => style2
    [2] => style3
    [3] => style4
    [4] => style5
);

$string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
           Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
           when an unknown printer took a galley of type and scrambled it to make a type specimen book.";

$result = str_replace($find,$replace,$string);
echo $result;
Max
  • 429
  • 1
  • 8
  • 25
  • 1
    What would you expect to happen if there are duplicates? – Nigel Ren May 20 '20 at 06:52
  • 1
    Do you want the first occurrence of "Lorem Ipsum" to be replaced with "style1" and the second with "style2"? – brombeer May 20 '20 at 06:54
  • @Nigel Ren Sorry didn't mention about the expected output. Should be something like find[0] replace with style[0], find[1] replace with style[1]. – Max May 20 '20 at 06:55
  • You need to replace only the first occurrence as you iterate over the `$find` and `$replace` arrays using something like the code in [this question](https://stackoverflow.com/questions/8272108/how-to-change-first-occurrence-of-word-in-a-string) – Nick May 20 '20 at 06:59
  • @Nick I tried what you suggested, but the `$string` is also iterating – Max May 20 '20 at 07:55

1 Answers1

2

You can use an implementation of str_replace_first such as described in this question and iterate over your $find and $replace arrays, replacing one occurrence of each value in the $find array only:

function str_replace_first($search, $replace, $subject) {
    if (($pos = strpos($subject, $search)) !== false) {
        return substr_replace($subject, $replace, $pos, strlen($search));
    }
    return $subject;
}

$result = $string;
foreach ($find as $key => $search) {
    $result = str_replace_first($search, $replace[$key], $result);
}
echo $result;

Output:

style1 is simply style4 text of the printing and style3 industry. 
style2 has been the industry's standard style5 text ever since the 1500s, 
when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95