正则表达式的解决方案是什么?PHP


Whats a regex solution for this? PHP

我想尝试替换以下标签的所有实例,并删除p和结束p之前和之后,但只有当类readmore被使用

<p><a class="readmore" href="http://www.google.com">My External Link</a></p>

您已经要求使用regex,但它并不是解析HTML的好解决方案。

DOMDocument/XPath

加载要处理的文档,找到要洗牌的元素,洗牌。类似这样的操作可能会起作用:

$document = new DOMDocument();
$document->loadHTMLFile(FILENAME);
$xpath = new DOMXPath($document);
$nodeList = $xpath->evaluate("//p[contains(a[@class='readmore'])]");
foreach ($nodeList as $node) {
    $node->parentNode->replaceChild($node->firstChild, $node);
}
<标题> XSLT h1> 参阅此答案以获取使用XSL样式表删除节点的帮助。你可以像这样构建一个模板:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output omit-xml-declaration="yes"/>
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="p[contains(a[@class='readmore'])]">
    <xsl:copy-of select="a"/>
  </xsl:template>
</xsl:stylesheet>
<标题> Regex h1> 果你真的想走毁灭之路,那么我想我无法阻止你。确保你已经在源代码控制中得到了所有的东西,并在提交之前检查差异…
preg_replace('#<p>(<a class="readmore" href="[^"]+">[^<]*<'/a>)<'/p>#', ''1');