Replacing Only the First Occurrence with str_replace
While there's no built-in str_replace function that limits its replacement to the first occurrence, a relatively straightforward solution exists without resorting to intricate hacks.
To achieve this, utilize the strpos function to locate the position of the substring within the main string. Once identified, employ substr_replace to modify the original string, specifying the occurrence position and the length of the substring. This method efficiently replaces the first occurrence without the overhead of regular expressions.
Code Example:
$haystack = "This is a sample string"; $needle = "is"; $replace = "was"; $pos = strpos($haystack, $needle); if ($pos !== false) { $newstring = substr_replace($haystack, $replace, $pos, strlen($needle)); } echo $newstring; // Output: "This was a sample string"
Bonus: To replace the last occurrence, substitute strpos with strrpos:
$pos = strrpos($haystack, $needle); if ($pos !== false) { $newstring = substr_replace($haystack, $replace, $pos, strlen($needle)); }
The above is the detailed content of How Can I Replace Only the First (or Last) Occurrence of a Substring in PHP?. For more information, please follow other related articles on the PHP Chinese website!