如何在php中的字符串中找到并替换第一个单词

如何在php中的字符串中找到并替换第一个单词

问题描述:

how to find and replace the first word from the string using php

eg:

 $str = 'Super World Hello World';
 replace($str,'Hello','Hi');

expected result should be 'Super World Hello World' as it does not match with first word.

eg2:

 $str = 'Hello World Hello World';
 replace($str,'Hello','Hi');

expected result should be 'Hi World Hello World' as it does match with first word.

please help

如何使用php查找和替换字符串中的第一个单词 p>

例如: p>

  $ str ='Super World Hello World'; 
 replace($ str,'Hello','Hi'); 
  code>   pre> 
 
 

预期结果应为'超级世界Hello World',因为它与第一个单词不匹配。 p>

eg2: p> $ str ='Hello World Hello World'; replace($ str,'Hello','Hi'); code> pre>

预期结果 应该是'Hi World Hello World',因为它与第一个单词匹配。 p>

请帮助 p> div>

Create a function for this, passed 3 arguments. Logic is convert string into array by explode() function and get first element of the array by using array_shift() function and compare with search string

function getReplacedStr($str, $searchStr, $replaceWith){
    $arr = explode(' ', $str);
$firstElement = array_shift($arr);
if($searchStr == $firstElement){
    $finalStr =  $replaceWith.' '.implode(' ', $arr);
}else{
    $finalStr = $str;
}
return $finalStr;
}
$replaceWith = 'Hi';
$searchStr = 'Hello';
$str = 'Hello World Hello World';
$str2 = 'Super World Hello World';

echo getReplacedStr($str, $searchStr, $replaceWith);
echo "
";
echo getReplacedStr($str2, $searchStr, $replaceWith);

Demo