问题
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:
- 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
回答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