使用php str_replace替换关键词,如何在替换的过程中优先满足最长的关键词>短词
比如有两个词【php技术,php】,我想让str_replace在执行替换时先替换【php技术】,让长的关键词优先,这个需要怎么写?求助
我现在的代码如下:
function str_replace_once($needle,$replace,$haystack) {
$pattern = '/]*>/is';
preg_match_all($pattern, $haystack, $matched);
if(empty($matched[0])){
$pos = strpos($haystack, $needle);
if ($pos === false) {
return $haystack;
}
return substr_replace($haystack, $replace, $pos, strlen($needle));
} else {
$arr = preg_split($pattern, $haystack);
$haystack_new = '';
$replace_time = 0;
foreach($arr as $key => $str){
$pos = strpos($str, $needle);
if ($pos === false || $replace_time > 0 || strpos($str, $needle.'') !== false) {
$haystack_new .= $str;
} else {
$haystack_new .= substr_replace($str, $replace, $pos, strlen($needle));
$replace_time = 1;
}
if(isset($matched[0][$key])) $haystack_new .= $matched[0][$key];
}
return $haystack_new;
}
}
怎么加上条件满足,最长的关键词>短词,【php技术】优先【php】
感谢灰色v碰触给出的答案,但是还是不知道怎么整合到我现有的代码中,继续求助!!