替换所有不在html-tags中的引号


Replace all quotes that are not in html-tags

目前我正在用特殊引号替换文本中的所有引号。但是我怎么能改变我的正则表达式,只有引号内的文本将被替换,而不是那些在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);

在正则表达式测试器中工作得很好的东西并不取代任何东西。我做错什么了吗?

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

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

Demo在这里
测试它-

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>

EDIT 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)

EDIT 2-
您已经正确地执行了preg_replace函数,但是在替换字符串中,您在双引号(")内使用了'1。这样做,您正在转义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)

阅读本页的"替换"部分以获得更清晰的信息。

EDIT 3-
一个正则表达式,它涵盖了可能不在标签内的文本-

'"([^<>]*?)'"(?=(?:[^>]*?(?:<|$)))
Demo

也可以使用negative forward:

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

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

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

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

替换:&raquo;'1&laquo;

在演示中,查看底部的替换。

参考

如何匹配(或替换)模式,除了s1, s2, s3…

使用这个正则表达式:

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

将匹配非html字符串。

然后对结果字符串

执行正则表达式