正则表达式捕获引号中的锚文本

Regex to capture anchor text in quotes

我正在尝试想出一个正则表达式来捕捉带有引用文本的锚点。例如:

<a href="www.example.com">this is "some quoted anchor text" example</a>
<a href="www.example.com">this is “another” example with different quote type</a>

我在这里想到了这个,但在我的 php 5.5.9 环境中感觉臃肿且无法正常工作:

https://regex101.com/r/NugIi2/3

我相信有更好的方法来捕捉这些引用的锚文本。

编辑:我应该提到我需要修复 AMP 页面上由于带引号的锚文本而出现的错误。所以在这种情况下不可能进行 DOM 操作。准确地说,我在后端使用带有 preg_replace 的 worpdress the_content 过滤器。

天啊...几小时后,我设法破解了一个有效的 DomDocument 解决方案!如果有更简洁的方法来保持准确性,欢迎大家告诉我。

代码:(Demo)

$html=<<<HTML
<a href="bla">123 "this" is asd</a>
<a href="bla">this should not be captured</a>
<a href="bla">no quotes in anchor text here</a>
<a href="bla">"445 is in quotes"</a>
<a href="bla">asd "blabla" sometimes</a>
<a href="bla">Je commence à avoir mal à la tête</a>
<a href="bla">something with quotes like “blabla” is bad</a>
HTML;

$dom = new DOMDocument;
$html=mb_convert_encoding($html,'HTML-ENTITIES',"UTF-8");   // for multibyte chars
$dom->loadHTML($html,LIBXML_HTML_NODEFDTD); // remove DOCTYPE, but allow <html><body> tags for stability
foreach($dom->getElementsByTagName('a') as $a){
    if(preg_match('~["“”]~u',$a->nodeValue)){
        $remove[]=$a;  // collect the nodes to remove
    }
} 
foreach($remove as $bad_a){
    $bad_a->parentNode->removeChild($bad_a); // remove targeted nodes
}
$result=mb_convert_encoding($dom->saveHTML(),"UTF-8",'HTML-ENTITIES');  // for multibyte chars
echo preg_replace(['~^<html><body>|</body></html>$~','~\R+~'],['',"\n"],$result);  // mop up <html> and <body> tags, and consecutive newline characters

输出:

<a href="bla">this should not be captured</a>
<a href="bla">no quotes in anchor text here</a>
<a href="bla">Je commence à avoir mal à la tête</a>

或者,如果您不想搞砸所有这些,这里有一个正则表达式单行代码,它将按预期执行:

代码:(Demo)

echo preg_replace('~<a[^>]*>.*?["“”].*?</a>\R?~u','',$html);

Pattern Demo