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
There's no version of it, but the solution isn't hacky at all.
$pos = strpos($haystack, $needle);
if ($pos !== false) {
$newstring = substr_replace($haystack, $replace, $pos, strlen($needle));
}
Pretty easy, and saves the performance penalty of regular expressions.
Bonus: If you want to replace last occurrence, just use strrpos
in place of strpos
.