替换所有不在html标签中的引号

时间:2014-03-23 10:37:55

标签: php html regex replace

目前我正在使用特殊引号替换文本中的所有引号。 但是,如何更改我的正则表达式,只会替换文本中的引号而不是html标记中使用的引号。

$text = preg_replace('/"(?=\w)/', "»", $text);
$text = preg_replace('/(?<=\w)"/', "&laquo;", $text);

我不适合正则表达式。问题是我需要用另一个符号替换起始引号而不是结束引号。

如果您确实需要更多信息,请说明。

感谢任何帮助!

修改

测试用例

<p>This is a "wonderful long text". At least it should be. Here we have a <a href="http://wwww.site-to-nowhere.com" target="_blank">link</a>.</p>

预期输出应为:

<p>This is a &raquo;wonderful long text&laquo;. At least it should be. Here we have a <a href="http://wwww.site-to-nowhere.com" target="_blank">link</a>.</p>

现在就是这样:

<p>This is a &raquo;wonderful long text&laquo;. At least it should be. Here we have a <a href=&raquo;http://wwww.site-to-nowhere.com&laquo; target=&raquo;_blank&laquo;>link</a>.</p>

编辑2

对于Kamehameha的回答,我已将以下代码添加到我的脚本中:

$text = preg_replace("/\"([^<>]*?)\"(?=[^>]+?<)/", "&raquo;\1&laquo;", $text);

在正则表达式测试中运行良好的功能并不能取代任何东西。我做错了什么?

4 个答案:

答案 0 :(得分:6)

此正则表达式适用于给定的字符串。

Search for   - "([^<>]*?)"(?=[^>]*?<)
Replace with - &raquo;\1&laquo;

演示here
测试它 -

INPUT - 
<p>This is a "wonderful long text". "Another wonderful ong text" At least it should be. Here we have a <a href="http://wwww.site-to-nowhere.com" target="_blank">link</a>.</p>

OUTPUT - 
<p>This is a &raquo;wonderful long text&laquo;. &raquo;Another wonderful ong text&laquo; At least it should be. Here we have a <a href="http://wwww.site-to-nowhere.com" target="_blank">link</a>.</p>

编辑1 -
在PHP中执行 -

$str = '<p>This is a "wonderful long text". "Another wonderful ong text" At least it should be. Here we have a <a href="http://wwww.site-to-nowhere.com" target="_blank">link</a>.</p>';
var_dump(preg_replace('/"([^<>]*?)"(?=[^>]*?<)/', '&raquo;\1&laquo', $str));

它的输出 -

/** OUTPUT **/
string '<p>This is a &raquo;wonderful long text&laquo. &raquo;Another wonderful ong text&laquo At least it should be. Here we have a <a href="http://wwww.site-to-nowhere.com" target="_blank">link</a>.</p>' (length=196)

编辑2 -
您已正确执行preg_replace函数,但在替换字符串中,您在Double引号中使用了\ 1(&#34;&#34;)。这样做,你正在逃避1本身并且不会被替换 为了更清楚,试试这个,看看会发生什么 -

echo '&raquo;\1&laquo;';
echo "&raquo;\1&laquo;";

第二个\ 1不应该是可见的 所以解决方案将是其中之一 -

preg_replace('/"([^<>]*?)"(?=[^>]*?<)/', '&raquo;\1&laquo;', $str)
preg_replace("/\"([^<>]*?)\"(?=[^>]*?<)/", "&raquo;\\1&laquo;", $str)
preg_replace("/\"([^<>]*?)\"(?=[^>]*?<)/", "&raquo;$1&laquo;", $str)

阅读this page中的替换部分,以便更清晰。

编辑3 -
包含可能未包含在tags-

中的文本的正则表达式
\"([^<>]*?)\"(?=(?:[^>]*?(?:<|$)))

演示here

答案 1 :(得分:1)

也可以使用否定前瞻:

(?![^<]*>)"([^"]+)"

替换为:&raquo;\1&laquo;

答案 2 :(得分:1)

为了记录,有一个简单的PHP解决方案没有被提及,并且有效地跳过了所有<a...</a>标签。

搜索:<a.*?<\/a>(*SKIP)(*F)|"([^"]*)"

替换:&raquo;\1&laquo;

Demo中,查看底部的替换。

参考

How to match (or replace) a pattern except in situations s1, s2, s3...

答案 3 :(得分:0)

使用此正则表达式:

(?<=^|>)[^><]+?(?=<|$)

这将匹配非html字符串。

然后对结果字符串

进行正则表达式
相关问题