How to change the first occurrence of a word in a string

advertisements

How do I do to change the first occurrence of a word in a string?

Example:

$a = "Yo! **Hello** this is the first word of Hello in this sentence";

to

$b = "Yo! **Welcome** this is the first word of Hello in this sentence";


This works, although a bit inefficient:

$a = "Yo! **Hello** this is the first word of Hello in this sentence";
$a = preg_replace('/Hello/', 'Welcome', $a, 1);

The other popular answer:

$b = str_replace('Hello', 'Welcome', $a, 1);

does not work. The fourth argument of str_replace should be a variable, which is passed by reference and str_replace will set it to the number of replacements made.

A better solution would be to extract two sub-strings from the input string:

  1. Sub-string before the first occurrence of Hello, call it $s1
  2. Sub-string after the first occurrence of Hello, call it $s2

One can use the strpos to get the position.

Result is $s1.'Welcome'.$s2