php
  • regex
  • preg-match
  • 2012-07-31 16 views 0 likes 
    0

    可能重复得到一个字符串的包装元素:
    get wrapping element using preg_match php如何使用正则表达式

    我希望得到一个封装了指定字符串的元素,所以比如:

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

    那么我怎样才能得到<p class='text'></p>包装字符串通过使用正则表达式pa ttern。

    回答

    0

    使用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); 
    
    相关问题