多个preg_replace,不替换替换

multiple preg_replace, don't replace replaced

我有这个示例输入:

text with magazine and sp

我必须找到 "magazine" 和 "sp" 并将它们包含在 "span" 标签中,如下输出:

text with <span class="highlight">magazine</span> and <span class="highlight">sp</span>


这是我的职能:

 function highlight($text, $phrase, $options = array()) {
if (empty($phrase)) {
 return $text;
}

$default = array(
 'format' => '<span class="highlight"></span>',
 'html' => false
);
$options = array_merge($default, $options);
extract($options);

if (is_array($phrase)) {
 $replace = array();
 $with = array();

 foreach ($phrase as $key => $segment) {
    $segment = "($segment)";
    if ($html) {
     $segment = "(?![^<]+>)$segment(?![^<]+>)";
    }

    $with[] = (is_array($format)) ? $format[$key] : $format;
    $replace[] = "|$segment|iu";
 }

 return preg_replace($replace, $with, $text);
} else {
 $phrase = "($phrase)";
 if ($html) {
    $phrase = "(?![^<]+>)$phrase(?![^<]+>)";
 }

 return preg_replace("|$phrase|iu", $format, $text);
}
}

但是使用这段代码我在输出中得到了这个:

text with <<span class="highlight">sp</span>an class="highlight">magazine<!--<span class="highlight"-->span> and <span class="highlight">sp</span>

有办法不替换“”的"sp"吗?

解决方案:

function highlight($text, $phrase, $options = array(), $lol = false) {
    $b = preg_replace("/".implode('|', $phrase)."\b/", "<span class=\"highlight\">[=10=]</span>", $text);
    return $b;
}

感谢#Julian