简体   繁体   中英

preg_match for nested html tags

I would like to catch all "dev" tags and their respective content, through php preg_match_all() but can't get the nested ones.

data:

<dev>aaa</dev> <dev>bbb</dev> <dev> ccc <dev>ddd</dev> </dev>

my expression so far:

|<dev>(.*)</dev>|Uis

thanks, for your help, b.

Don't use regular expressions for parsing. Use a real parser like DOMDocument or SimpleXML :

$xml = simplexml_load_string('<root>'.$str.'</root>');

You need to have a recursive matching pattern:

/<dev>(.*|(?R))<\/dev>/i

That will just suck up any nested elements, so if you want to then parse those, you will have to run the function again on $matches[1]

The * is a greedy operator, consumes as many characters as possible. You should use the *? non-greedy version instead to find the smallest possible matches. Maybe regexes are not the best tools to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM