get wrapping element using preg_match php

梦想的初衷 提交于 2019-12-02 03:58:20

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

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

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.

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