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]-->
对于上述内容,我需要一些帮助来编写代码,以用--
替换所有出现的双短划线(—
)。
但是,它不应该替换html元素中任何属性的双短划线。例如,不应替换类名(my--class-name--here
)和ID名称(id="some--id"
)中的双短划线。
而且,它也不应该取代<!--[if IE 9]>
和<![endif]-->
答案 0 :(得分:3)
如果您想要在<
和>
之外替换单行,则可以使用以下内容。
$html = preg_replace('~<[^>]*>(*SKIP)(*F)|--~', '—', $html);
我们的想法是跳过位于左右括号中的任何内容。
在交替运算符的左侧,我们匹配我们不想要的子模式。使其失败并强制正则表达式引擎不使用回溯控制动词重试子字符串。
答案 1 :(得分:1)
使用否定前瞻来匹配不在任何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]-->