如何更改字符串中第一次出现的单词?如何更改字符串中第一次出现的单词
实施例:
$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
构建:
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
这是最好的紧凑性和表演:“如果获得通过,这将被设置为替换数:
if(($offset=strpos($string,$replaced))!==false){
$string=substr_replace($replaced,$replacer,$offset,strlen($replaced));
}
没有正则表达式
第一个解决方案,实际工作;) – str
刚刚看到你的编辑 - 我已经实现你的第二个解决方案,并张贴它作为答案:) – nickb
*看到效率低下的答案* ...在生产代码中使用它。为什么?比第二个建议的解决方案更容易理解:) – Dennis