匹配没有正则表达式的短代码


Matching shortcodes without regex

我已经读到了很多,使用正则表达式不是获取和操作html的最聪明的方法,你应该利用DOMDocument。我从文档和此处重构了一些代码,并创建了两个函数the_content()拆分为文本和标签。第一个函数删除特定标记并返回不带标记的内容,第二个函数返回没有其他内容的标记内容

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真的很糟糕,并且匹配所有短代码。

我找到了很多使用正则表达式的例子,但没有一个使用 DOM 的例子。以下是两个短代码示例

  • [audio mp3="http://localhost/wordpress/wp-content/uploads/2014/09/Aha-The-Sun-Always-Shines-On-TV.mp3"][/audio]

  • [gallery ids="734,731,725,721"]

如何匹配音频短代码

以及如何匹配库短代码。这是否可能在不使用正则表达式和使用 DOM 的情况下以及如何使用?

仅使用 DOM 无法隔离短代码。

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

Shadow DOM是原生HTML短代码的新兴标准。截至今天,本机支持参差不齐。如果你想用 DOM 可解析的东西替换你的短代码,这将是你要走的路。