我已经读过很多书,使用正则表达式不是获取和操作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替换您的短代码,这就是方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句