可能重复:
使用preg_match-php-获取包装元素
我想要获得包装指定字符串的元素,例如:
$string = "My String";
$code = "<div class="string"><p class='text'>My String</p></div>";
那么,我如何能够通过使用regex模式匹配字符串来获得包装字符串的<p class='text'></p>
呢。
使用PHP的DOM类可以做到这一点。
$html = new DomDocument();
// load in the HTML
$html->loadHTML('<div class="string"><p class=''text''>My String</p></div>');
// create XPath object
$xpath = new DOMXPath($html);
// get a DOMNodeList containing every DOMNode which has the text 'My String'
$list = $xpath->evaluate("//*[text() = 'My String']");
// lets grab the first item from the list
$element = $list->item(0);
现在我们有了完整的<p>
-标签。但我们需要删除所有子节点。这里有一个小功能:
function remove_children($node) {
while (($childnode = $node->firstChild) != null) {
remove_children($childnode);
$node->removeChild($childnode);
}
}
让我们使用这个函数:
// remove all the child nodes (including the text 'My String')
remove_children($element);
// this will output '<p class="text"></p>'
echo $html->saveHTML($element);