Home >Backend Development >PHP Tutorial >How Can I Replace Only the First Occurrence of a Substring in PHP?
Replacing Only the First Occurrence with str_replace
There's no built-in variant of str_replace() that exclusively modifies a single occurrence. However, an elegant solution exists without resorting to convoluted approaches.
To limit replacement to the first match, employ the following procedure:
$pos = strpos($haystack, $needle); if ($pos !== false) { $newstring = substr_replace($haystack, $replace, $pos, strlen($needle)); }
This method is highly efficient, sidestepping the potential performance hit associated with regular expressions.
Bonus:
For replacing the last occurrence, simply replace strpos() with strrpos() in the above code.
The above is the detailed content of How Can I Replace Only the First Occurrence of a Substring in PHP?. For more information, please follow other related articles on the PHP Chinese website!