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