如何更改字符串中单词的第一次出现 [英] How to change first occurrence of word in a string
本文介绍了如何更改字符串中单词的第一次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何更改字符串中单词的第一次出现?
示例:
$a = "Yo!**Hello** 这是这句话中Hello的第一个词";
到
$b = "Yo! **Welcome** 这是这句话中Hello的第一个词";
解决方案
这有效,虽然有点低效:
$a = "Yo!**Hello** 这是这句话中Hello的第一个词";$a = preg_replace('/Hello/', '欢迎', $a, 1);
另一个流行的答案:
$b = str_replace('你好', '欢迎', $a, 1);
不起作用.str_replace
的第四个参数应该是一个变量,通过引用传递,str_replace
会将其设置为替换次数.>
更好的解决方案是从输入字符串中提取两个子字符串:
- 第一次出现
Hello
之前的子串,称之为$s1
- 第一次出现
Hello
后的子串,称之为$s2
可以使用strpos
来获取位置.
结果是 $s1.'Welcome'.$s2
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:
- Sub-string before the first occurrence of
Hello
, call it$s1
- 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
这篇关于如何更改字符串中单词的第一次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文