How to change first occurrence of word in a string

梦想与她 提交于 2020-06-16 02:58:24

问题


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";

回答1:


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:

  1. Sub-string before the first occurrence of Hello, call it $s1
  2. 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




回答2:


Just use substr twice with strpos.

$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));

Demo




回答3:


This is the best for compactness and performances:

if(($offset=strpos($string,$replaced))!==false){
   $string=substr_replace($replaced,$replacer,$offset,strlen($replaced));
}

Replace only the first occurrence without the overload of the regular expressions




回答4:


Use substr_replace().




回答5:


Use str_replace('Hello','Welcome',$a,1);




回答6:


Build It:

function str_replace_first($search, $replace, $source) {

  $explode = explode( $search, $source );
  $shift = array_shift( $explode );
  $implode = implode( $search, $explode );
  return $shift.$replace.$implode;

}

Call it:

$msg = "Yo! **Hello** this is the first word of Hello in this sentence";
echo str_replace_first( 'Hello', 'Welcome', $msg );

Try It:

http://sandbox.onlinephpfunctions.com/code/399ec70333832423c79d36a42032124d5c296d27



来源:https://stackoverflow.com/questions/8272108/how-to-change-first-occurrence-of-word-in-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!