今天遇到一个问题 需要只替换字符串一次,而不是全部替换,str_replace这个函数会替换所有的pattern,所以思考如何做到php的只替换一次。
方案1:
正则替换preg_replace (懒惰替换)
方案2:
用strpos判断 pattern 在不在 字符串内, 如果在 利用substr_replace 找到pattern的位置段, 利用位置段来替换。
if (!function_exists('str_replace_once')) {
function str_replace_once($needle, $replace, $haystack) {
$pos = strpos($haystack, $needle);
if ($pos === false) {
return $haystack;
}
return substr_replace($haystack, $replace, $pos, strlen($needle));
}
}