多个preg_replace,不要替换被替换的

时间:2015-05-04 13:41:41

标签: php regex preg-replace

我有这个例子输入:

text with magazine and sp

我必须找到"杂志"和" 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">\1</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>

有一种方法可以替代&#34; sp&#34; of&#34;&lt; span&gt;&#34;?

1 个答案:

答案 0 :(得分:0)

解决方案:

DesiredCapabilities capabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
capabilities.setCapability("chrome.binary", "/path/to/chromedriver.exe");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
webDriver = new ChromeDriver(capabilities);

感谢#Julian