get wrapping element using preg_match php

跟風遠走 提交于 2019-12-02 08:16:21

问题


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 = "<div><p class='text'>My text</p><span>My text</span></div>";

So i need to create a function that will return the element wrapping the string like:

$element = get_wrapper($string, $html);

function get_wrapper($str, $code){
    //code here that has preg_match and return the wrapper element
}

The returned value will be array since it has 2 possible returning values which are <p class='text'></p> and <span></span>

Anyone can give me a regex pattern on how to get the HTML element that wraps the given string?

Thanks! Answers are greatly appreciated.


回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/11733733/get-wrapping-element-using-preg-match-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!