xlfm22 发表于 2017-4-14 10:22:07

php替换字符串中首个字符串[不重复替换]

利用正则表达式的方法替换字符串,并且只替换首个字符串,其余重复的不替换,可以利用这方法给文章关键词替换上连接




/**
+----------------------------------------------------------
* 只替换字符串中关键字一次
+----------------------------------------------------------
* @param string $needle 需替换的字符串
* @param string $replace 目标字符串
* @param string $haystack 原始字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
function str_replace_once($needle, $replace, $haystack) {
$pos = strpos($haystack, $needle);
if ($pos === false) {
return $haystack;
}
return substr_replace($haystack, $replace, $pos, strlen($needle));
}


 

海口  http://www.souhaikou.com
页: [1]
查看完整版本: php替换字符串中首个字符串[不重复替换]