繁体   English   中英

如何使用正则表达式获取字符串的包装元素

[英]How to get wrapping element of a string using regex [duplicate]

可能重复:
使用preg_match php获取包装元素

我想获取包装指定字符串的元素,因此示例:

$string = "My String";
$code = "<div class="string"><p class='text'>My String</p></div>";

因此,我如何通过使用正则表达式模式匹配它来获取<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> -tag。 但是我们需要删除所有子节点。 这里有个小功能:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM