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

来源:互联网 发布:limit mysql 性能 编辑:程序博客网 时间:2024/05/21 22:59
利用正则表达式的方法替换字符串,并且只替换首个字符串,其余重复的不替换,可以利用这方法给文章关键词替换上连接

/** +---------------------------------------------------------- * 只替换字符串中关键字一次 +---------------------------------------------------------- * @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));}
 
原创粉丝点击