如何更改字符串中第一次出现的单词

Fre*_*rik 3 php string replace

如何更改字符串中单词的第一次出现?

例:

$a = "Yo! **Hello** this is the first word of Hello in this sentence";
Run Code Online (Sandbox Code Playgroud)

$b = "Yo! **Welcome** this is the first word of Hello in this sentence";
Run Code Online (Sandbox Code Playgroud)

cod*_*ict 11

这有效,虽然有点效率低:

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

另一个流行的答案:

$b = str_replace('Hello', 'Welcome', $a, 1);
Run Code Online (Sandbox Code Playgroud)

不起作用.第四个参数str_replace应该是一个变量,它通过引用传递,str_replace并将其设置为所做的替换次数.

更好的解决方案是从输入字符串中提取两个子字符串:

  1. 在第一次出现之前的子串Hello,调用它$s1
  2. 第一次出现后的子串Hello,调用它$s2

人们可以用它strpos来获得这个位置.

结果是 $s1.'Welcome'.$s2