Using str_replace so that it only acts on the first match?

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.

Leave a Comment