0

我需要一些帮助。我研究了正则表达式,但还没有完全理解它的实现。如果父级包含给定的类或ID,我需要一个片段来删除所有标签及其子级。

例子:

<?php

function remove_tag($find="",$html)
{
    # Remove multiple #IDs and classes at once

    # When given a string (separating objects with a comma)
    if (is_string($find))
    {
        $objects = explode(',', str_replace(' ', '', $find);
    } else if (is_array($find)) {
        $objects = $find;
    }

    foreach ($objects as $object)
    {
        # If ID
        if (substr($object,0,1) == '#')
        {
            # regex to remove an id
            # Ex: '<ANYTAG [any number of attributes] id='/"[any number of ids] NEEDLE [any number of ids]'/" [any number of attributes]>[anything]</ENDTAG [anything]>'

        }

        if (substr($object,0,1) == '.')
        {
            # remove a class
            # Ex: '<ANYTAG [any number of attributes] class='/"[any number of classes] NEEDLE [any number of classes]'/" [any number of attributes]>[anything]</ENDTAG [anything]>'
        }

        # somehow remove it from the $html variable?
    }
}

抱歉,如果这是一个新手问题,谢谢您的宝贵时间!:)

-拍

4

1 回答 1

2

您可以使用 XPath 而不是正则表达式来查找文档中要删除的所有元素。

DOMDocumentXPath对我来说似乎是一个好的开始。

您可以使用DOMNode::removeChild()方法来删除子节点,并使用DOMXPath类来评估 XPath,以获得您需要删除的节点。

于 2013-02-16T00:24:03.923 回答