如何更改字符串中第一次出现的单词?
示例:
$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";
答案 0 :(得分:11)
虽然效率有点低,但仍有效:
$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
答案 1 :(得分:4)
$a = "Yo! **Hello** this is the first word of Hello in this sentence";
$search = "Hello";
$replacement = "Welcome";
$b = substr( $a, 0, strpos( $a, $search)) . $replacement . substr( $a, strpos( $a, $search) + strlen( $search));
答案 2 :(得分:1)
这是紧凑和表演的最佳选择:
if(($offset=strpos($string,$replaced))!==false){
$string=substr_replace($replaced,$replacer,$offset,strlen($replaced));
}
仅替换第一次出现而没有正则表达式的重载
答案 3 :(得分:0)
答案 4 :(得分:0)
使用str_replace('Hello','Welcome',$a,1);
答案 5 :(得分:0)
构建它:
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