Matching content outside blockquote tag

时间:2016-12-09 12:59:33

标签: php html regex preg-match

I'm looking to do the opposite of this.

<?php
// get the content
$block = get_the_content();

// check and retrieve blockquote
if(preg_match('~<blockquote>([\s\S]+?)</blockquote>~', $block, $matches))

// output blockquote
echo '<p><span>'.$matches[1].'</span></p>';
?>

How to show the content outside of the blockquote.

1 个答案:

答案 0 :(得分:2)

You really shouldn't use regular expression for HTML-parsing。我建议您使用phpQuery来解决您的问题以及将来出现的任何其他类似问题。 phpQuery的工作方式与jQuery类似,可以选择HTML中的元素并进行修改。在phpQuery中你可以这样做:

$markup = '<div><span>Hello</span><blockquote>Remove me!</blockquote>World<div/>';
$doc = phpQuery::newDocumentHTML($markup);
$doc['blockquote']->remove();
echo $doc;

因此,您将HTML内容加载到phpQuery,选择blockquote,将其删除,然后打印出更改后的字符串。

如果您仍然坚持使用正则表达式,那么它是:

$block = preg_replace('~<blockquote>([\s\S]+?)</blockquote>~', '', $block);
echo $block;