利用正则表达式的方法替换字符串,并且只替换首个字符串,其余重复的不替换,可以利用这方法给文章关键词替换上连接
/**
+----------------------------------------------------------
* 只替换字符串中关键字一次
+----------------------------------------------------------
* @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
正则表达式替换技巧
本文介绍了一种使用正则表达式的技巧,该技巧能够帮助开发者仅替换字符串中的首次出现的关键字,这对于需要精确控制替换行为的应用场景非常有用。
2403

被折叠的 条评论
为什么被折叠?



