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
Here's a simple class I created to wrap our slightly modified str_replace() functions.
Our php::str_rreplace() function also allows you to carry out a reverse, limited str_replace() which can be very handy when trying to replace only the final X instance(s) of a string.
These examples both use preg_replace().
' with ''
*
* @param string $find
* @param string $replace
* @param string $subject
* @param int $replacement_limit | -1 to replace all references
*
* @return string
*/
public static function str_replace($find, $replace, $subject, $replacement_limit = -1) {
$find_pattern = str_replace('/', '\/', $find);
return preg_replace('/' . $find_pattern . '/', $replace, $subject, $replacement_limit);
}
/**
* str_replace() from the end of a string that can also be limited e.g. replace only the last instance of '