get wrapping element using preg_match php

前端 未结 3 1098
无人共我
无人共我 2021-01-24 16:31

I want a preg_match code that will detect a given string and get its wrapping element. I have a string and a html code like:

$string = \"My text\";
$html = \"<         


        
3条回答
  •  半阙折子戏
    2021-01-24 16:58

    It's bad idea use regex for this task. You can use DOMDocument

    $oDom = new DOMDocument('1.0', 'UTF-8');
    $oDom->loadXML("
    " . $sHtml ."
    "); get_wrapper($s, $oDom);

    after recursively do

    function get_wrapper($s, $oDom) {
        foreach ($oDom->childNodes AS $oItem) {
            if($oItem->nodeValue == $s) {
                //needed tag - $oItem->nodeName
            }
            else {
                get_wrapper($s, $oItem);    
            }
        }
    }
    

提交回复
热议问题