這是我在網上找到的一個方法,挺好的,它的作用就是:當字符串A多次出現在字符串B中,而我們需要將B字符串中的第一個字符串A給替換成別的字符串時用到,比如在文章內容裏給關鍵詞加鏈接就需要用到它。
$needle=>字符串A,$replace=>將字符串A要替換成的新字符串,$haystack=>字符串B;
使用實例:echo str_replace_once("賢誠網","賢誠網","賢誠網——賢誠CSM官方網站");
function str_replace_once($needle, $replace, $haystack) {//只替換一次字符串
$pos = strpos($haystack, $needle);
if ($pos === false) {
return $haystack;
}
return substr_replace($haystack, $replace, $pos, strlen($needle));
}