I want to search and replace the first word with another in php like as follows:
$str="nothing inside";
Replace 'nothing' to 'something' by search and replace without using substr
output should be: 'something inside'
Use the replace() method to replace the first occurrence of a character in a string. The method takes a regular expression and a replacement string as parameters and returns a new string with one or more matches replaced.
The str_replace() is a built-in function in PHP and is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively.
Use preg_replace()
with a limit of 1:
preg_replace('/nothing/', 'something', $str, 1);
Replace the regular expression /nothing/
with whatever string you want to search for. Since regular expressions are always evaluated left-to-right, this will always match the first instance.
on the man page for str_replace (http://php.net/manual/en/function.str-replace.php) you can find this function
function str_replace_once($str_pattern, $str_replacement, $string){
if (strpos($string, $str_pattern) !== false){
$occurrence = strpos($string, $str_pattern);
return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern));
}
return $string;
}
usage sample: http://codepad.org/JqUspMPx
try this
preg_replace('/^[a-zA-Z]\s/', 'ReplacementWord ', $string)
what it does is select anything from start till first white space and replace it with replcementWord . notice a space after replcementWord. this is because we added \s
in search string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With