I want a version of str_replace()
that only replaces the first occurrence of $search
in the $subject
. Is there an easy solution to thi
You can use this:
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;
}
Found this example from php.net
Usage:
$string = "Thiz iz an examplz";
var_dump(str_replace_once('z','Z', $string));
Output:
ThiZ iz an examplz
This may reduce the performance a little bit, but the easiest solution.