匹配没有正则表达式的简码

Matching shortcodes without regex

我读过很多关于使用正则表达式不是获取和操作 html 的最聪明的方法,您应该使用 DOMDocument。我重构了文档和 here 中的一些代码,并创建了两个函数来将 the_content() 拆分为文本和标签。第一个函数删除特定标签和 returns 没有标签的内容,第二个函数 returns 没有其他内容的标签内容

function get_content_without( $html, $tag )
{
    $dom = new DOMDocument;
    $dom->loadHTML( $html );

    $dom_x_path = new DOMXPath( $dom );
    while ($node = $dom_x_path->query( $tag )->item(0)) {
        $node->parentNode->removeChild( $node );
    }
    return $dom->saveHTML();
}

function get_html_tag_content( $html, $tag )
{
    $document = new DOMDocument();
    $document->loadHTML( $html );  

    $tags = [];
    $elements = $document->getElementsByTagName( $tag );
    if ( $elements ) {
        foreach ( $elements as $element ) {
            $tags[] = $document->saveHtml($element);
        }   
    }   
    return $tags;
}

概念证明:(这里我们从 a 标签分离文本

$html = '<a href="http://localhost/wordpress/image3/tags-sidebar/" rel="attachment wp-att-731">
        <img src="http://localhost/wordpress/wp-content/uploads/2014/12/tags-sidebar.jpg" alt="tags sidebar" width="318" height="792" class="alignright size-full wp-image-731" />
    </a>
    Cras malesuada turpis et augue feugiat, eget mollis tellus elementum. 
    Nunc posuere mattis arcu, ut varius ipsum molestie in. 
    Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; 
    Morbi ultricies tincidunt odio nec suscipit. Sed porttitor metus ut tincidunt interdum. 
    Etiam lobortis mollis augue at aliquam. Nunc venenatis elementum quam sed elementum. 
    Pellentesque congue pellentesque orci, vel convallis augue semper vitae';

?><pre><?php var_dump(get_html_tag_content($html, 'a')); ?></pre><?php  
?><pre><?php var_dump(get_content_without($html, '//a')); ?></pre><?php 

我的问题是,在 Wordpress 中是否有类似于匹配和删除短代码的功能。内置功能是 Wordpress 真的很糟糕并且匹配所有简码。

我发现很多使用正则表达式的示例,但是 none 使用 DOM。这里有两个短代码的例子

如何匹配音频短代码以及如何匹配图库短代码。如果不使用正则表达式并使用 DOM 这可能吗?

仅使用 DOM 是不可能隔离简码的。

字符[]在HTML或XML中没有特殊含义。因此,对于 DOM 解析器,[shortcode] 与上面示例文本中的 ipsum 没有什么不同。它只是文本节点的另一部分,因此定位它们的唯一方法是通过字符串函数,例如使用正则表达式。

Shadow DOM is the up-and-coming standard for what are essentially native HTML shortcodes. As of today, native support is spotty。如果你想用 DOM 可解析的东西替换你的短代码,这就是你要走的路。