get wrapping element using preg_match php

前端 未结 3 1058
无人共我
无人共我 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:53

    The simple pattern would be the following, but it assumes a lot of things. Regexes shouldn't be used with these. You should look at something like the Simple HTML DOM parser which is more intelligent.

    Anyway, the regex that would match the wrapper tags and surrounding html elements is as follows.

     /[A-Za-z'= <]*>My text<[A-Za-z\/>]*/g
    
    0 讨论(0)
  • 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("<div>" . $sHtml ."</div>");
    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);    
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-24 16:58

    Even if regex is never the correct answer in the domain of dom parsing, I came out with another (quite simple) solution

    <[^>/]+?>My String</.+?>
    

    if the html is good (ie it has closing tags, < is replaced with < & so on). This way you have in the first regex group the opening tag and in the second the closing one.

    0 讨论(0)
提交回复
热议问题