【发布时间】:2012-01-06 12:15:59
【问题描述】:
如何更改字符串中单词的第一次出现?
例子:
$a = "Yo! **Hello** this is the first word of Hello in this sentence";
到
$b = "Yo! **Welcome** this is the first word of Hello in this sentence";
【问题讨论】:
如何更改字符串中单词的第一次出现?
例子:
$a = "Yo! **Hello** this is the first word of Hello in this sentence";
到
$b = "Yo! **Welcome** this is the first word of Hello in this sentence";
【问题讨论】:
这行得通,虽然效率有点低:
$a = "Yo! **Hello** this is the first word of Hello in this sentence";
$a = preg_replace('/Hello/', 'Welcome', $a, 1);
另一个流行的答案:
$b = str_replace('Hello', 'Welcome', $a, 1);
不起作用。 str_replace 的第四个参数应该是一个变量,它通过引用传递,str_replace 会将其设置为替换次数。
更好的解决方案是从输入字符串中提取两个子字符串:
Hello之前的子字符串,叫它$s1
Hello后的子串,称它为$s2
可以使用strpos获取位置。
结果是$s1.'Welcome'.$s2
【讨论】:
这对于紧凑性和性能来说是最好的:
if(($offset=strpos($string,$replaced))!==false){
$string=substr_replace($replaced,$replacer,$offset,strlen($replaced));
}
只替换第一次出现而不重载正则表达式
【讨论】:
$string = 'the quick brown fox eats the brown sugar.'; $replaced = 'brown'; $replacer = 'yellow'; 。我得到的结果: brownyellow 。我想要的结果:敏捷的黄狐吃红糖。对不起,我错过了什么吗?谢谢
【讨论】:
使用str_replace('Hello','Welcome',$a,1);
【讨论】:
构建它:
function str_replace_first($search, $replace, $source) {
$explode = explode( $search, $source );
$shift = array_shift( $explode );
$implode = implode( $search, $explode );
return $shift.$replace.$implode;
}
叫它:
$msg = "Yo! **Hello** this is the first word of Hello in this sentence";
echo str_replace_first( 'Hello', 'Welcome', $msg );
试试看:
http://sandbox.onlinephpfunctions.com/code/399ec70333832423c79d36a42032124d5c296d27
【讨论】: