该正则表达式适用于给定的字符串。
Search for - "([^<>]*?)"(?=[^>]*?<)
Replace with - »\1«
Demo here http://regex101.com/r/uD4tK6
测试它 -
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>
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('/"([^<>]*?)"(?=[^>]*?<)/', '»\1«', $str));
它的输出 -
/** 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)
EDIT 2-
您已执行了preg_replace
功能正常,但在替换字符串中,您在双引号 ("") 内使用了 \1。这样做,你就逃避了 1 本身,并且它不会被替换。
为了更清楚地说明这一点,尝试一下,看看会发生什么 -
echo '»\1«';
echo "»\1«";
第二个 \1 不应该是可见的。
所以解决方案是其中之一 -
preg_replace('/"([^<>]*?)"(?=[^>]*?<)/', '»\1«', $str)
preg_replace("/\"([^<>]*?)\"(?=[^>]*?<)/", "»\\1«", $str)
preg_replace("/\"([^<>]*?)\"(?=[^>]*?<)/", "»$1«", $str)
阅读中的替换部分这一页 https://www.php.net/preg_replace为了更清楚。
EDIT 3-
包含可能未包含在标签内的文本的正则表达式 -
\"([^<>]*?)\"(?=(?:[^>]*?(?:<|$)))
Demo here http://regex101.com/r/xT0vZ1