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

Tob*_*lbs 4 html php regex replace

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

$text = preg_replace('/"(?=\w)/', "»", $text);
$text = preg_replace('/(?<=\w)"/', "&laquo;", $text);
Run Code Online (Sandbox Code Playgroud)

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

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

任何帮助表示赞赏!

编辑

测试用例

<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>
Run Code Online (Sandbox Code Playgroud)

预期产量应为:

<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>
Run Code Online (Sandbox Code Playgroud)

现在它是这样的:

<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>
Run Code Online (Sandbox Code Playgroud)

编辑2

感谢Kamehameha的答案,我已将以下代码添加到我的脚本中:

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

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

Kam*_*eha 6

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

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

在这里演示
测试它 -

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>
Run Code Online (Sandbox Code Playgroud)

编辑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));
Run Code Online (Sandbox Code Playgroud)

它的输出 -

/** 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)
Run Code Online (Sandbox Code Playgroud)

编辑2-
您已preg_replace正确执行该功能,但在替换字符串中,您在双引号("")中使用了\ 1.这样做,你正在逃避1本身并且不会被替换.
为了更清楚,试试看看会发生什么 -

echo '&raquo;\1&laquo;';
echo "&raquo;\1&laquo;";
Run Code Online (Sandbox Code Playgroud)

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

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

请阅读此页面中的"替换"部分以获得更清晰的信息.

编辑3-
一个正则表达式,涵盖可能未包含在标签内的文本 -

\"([^<>]*?)\"(?=(?:[^>]*?(?:<|$)))
Run Code Online (Sandbox Code Playgroud)

在这里演示