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并将其设置为所做的替换次数.
更好的解决方案是从输入字符串中提取两个子字符串:
Hello,调用它$s1Hello,调用它$s2人们可以用它strpos来获得这个位置.
结果是 $s1.'Welcome'.$s2
| 归档时间: |
|
| 查看次数: |
8820 次 |
| 最近记录: |