Tob*_*lbs 4 html php regex replace
目前我正在使用特殊引号替换文本中的所有引号.但是,如何更改我的正则表达式,只会替换文本中的引号而不是html标记中使用的引号.
$text = preg_replace('/"(?=\w)/', "»", $text);
$text = preg_replace('/(?<=\w)"/', "«", $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 »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 »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)
编辑2
感谢Kamehameha的答案,我已将以下代码添加到我的脚本中:
$text = preg_replace("/\"([^<>]*?)\"(?=[^>]+?<)/", "»\1«", $text);
在正则表达式测试中运行良好的东西并不能取代任何东西.我做错了什么吗?
这个正则表达式适用于给定的字符串.
Search for - "([^<>]*?)"(?=[^>]*?<)
Replace with - »\1«
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 »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>
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('/"([^<>]*?)"(?=[^>]*?<)/', '»\1«', $str));
Run Code Online (Sandbox Code Playgroud)
它的输出 -
/** OUTPUT **/
string '<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>' (length=196)
Run Code Online (Sandbox Code Playgroud)
编辑2-
您已preg_replace正确执行该功能,但在替换字符串中,您在双引号("")中使用了\ 1.这样做,你正在逃避1本身并且不会被替换.
为了更清楚,试试看看会发生什么 -
echo '»\1«';
echo "»\1«";
Run Code Online (Sandbox Code Playgroud)
第二个\ 1不应该是可见的.
所以解决方案将是其中之一 -
preg_replace('/"([^<>]*?)"(?=[^>]*?<)/', '»\1«', $str)
preg_replace("/\"([^<>]*?)\"(?=[^>]*?<)/", "»\\1«", $str)
preg_replace("/\"([^<>]*?)\"(?=[^>]*?<)/", "»$1«", $str)
Run Code Online (Sandbox Code Playgroud)
请阅读此页面中的"替换"部分以获得更清晰的信息.
编辑3-
一个正则表达式,涵盖可能未包含在标签内的文本 -
\"([^<>]*?)\"(?=(?:[^>]*?(?:<|$)))
Run Code Online (Sandbox Code Playgroud)
在这里演示