将所有出现的双短划线 (--) 替换为 —,但不要将属性或注释内部替换


Replace all occurrence of double dash (--) with —, but not inside attributes or comments

some text here
<span class="my--class-name--here" id="some--id">some -- text--here</span> 
test text--here
<div class="another--class-name">test --test</div>
<!--[if IE 9]><video style="display: none;"><![endif]-->

对于上述内容,我需要一些帮助编写代码以将所有出现的双破折号(--(替换为&mdash;

但是,它不应该替换 html 元素内任何属性的双破折号。例如,类名(my--class-name--here(和id名(id="some--id"(中的双破折号不应被替换。而且,它也不应该取代<!--[if IE 9]><![endif]-->中的双破折号

如果您希望在

<> 之外替换单行,您可以使用以下内容。

$html = preg_replace('~<[^>]*>(*SKIP)(*F)|--~', '—', $html);

这个想法是跳过位于左括号和右括号字符之间的任何内容。

在交替运算符的左侧,我们匹配我们不想要的子模式。使其失败并强制正则表达式引擎不使用回溯控制谓词重试子字符串。

工作演示

使用负前瞻来匹配不在任何 html 标记内的--

--(?![^><]*>)

将匹配的--替换为

演示

<?php
$string = <<<EOT
some text here
<span class="my--class-name--here" id="some--id">some -- text--here</span> 
test text--here
<div class="another--class-name">test --test</div>
<!--[if IE 9]><video style="display: none;"><![endif]-->
EOT;
echo preg_replace('~--(?![^><]*>)~', '—', $string);
?>

输出:

some text here
<span class="my--class-name--here" id="some--id">some — text—here</span> 
test text—here
<div class="another--class-name">test —test</div>
<!--[if IE 9]><video style="display: none;"><![endif]-->