【问题标题】:regex to remove anchor tags if it is outside of myclass如果它在 myclass 之外,则正则表达式删除锚标签
【发布时间】:2016-06-10 06:25:18
【问题描述】:

如果给定字符串不在我的班级范围内,我想使用正则表达式从给定字符串中删除锚标记。

输入:

<p>Hi Hello <a href="#">World</a></p>. This is <div class="myclass">testing <a href="#">content</a>. some more content</div>. One more <a href="#"> Link </a>.

输出:

<p>Hi Hello </p>. This is <div class="myclass"> testing <a href="#">content</a>. some more content</div>. One more .

提前致谢。

【问题讨论】:

  • 如果没有相同类型的嵌套标签,请尝试(*SKIP)(*F) like this,但通常最好使用@Jan 提供的答案 Imho 之类的解析器。正则表达式在输入较大时会变得缓慢且不可靠。

标签: php regex


【解决方案1】:

您可以(并且应该,顺便说一句)使用DOM 方式(如果不是不可能的话,单独使用正则表达式会很困难)。这里的方法是寻找没有祖先 div.myclass 的超链接并从 DOM 中删除它们:

<?php

$html = <<<EOF
<p>Hi Hello <a href="#">World</a></p>.
This is <div class="myclass">testing <a href="#">content</a>. some more content</div>.
One more <a href="#"> Link </a>.
EOF;

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXpath($dom);
$links = $xpath->query("//a[not(ancestor::div[@class='myclass'])]");

// Loop over them
foreach ($links as $link) {
    $link->parentNode->removeChild($link);
}

// just to test it out
echo $dom->saveHTML();
?>

看到它working on ideone.com


看看 cmets,您似乎仍然喜欢正则表达式方式(为什么?)。
PCRE 有一个 (*SKIP)(*FAIL) 机制,它也适用于这个(简化的)示例:
<div\ class="myclass">
[\s\S]*?
</div>
(*SKIP)(*FAIL)
|
<a[^>]*>.*?</a>

查看此 one on regex101.com 的演示。
提示:对于嵌套的 HTML 字符串 (&lt;div&gt;&lt;div&gt;) 或类似 @987654330 的属性不起作用 @ 都是有效的 HTML 表达式(显然)。

【讨论】:

  • 嗨@Jan...谢谢你的努力。我正在寻找不是以DOM方式的正则表达式。
  • @Ramesh:它会导致死胡同:)
  • 嗨@Jan...真的是一个很好的解决方案。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-11
  • 2018-02-08
  • 1970-01-01
  • 2011-04-16
  • 2013-01-07
相关资源
最近更新 更多