php - How to preg_match all style tags? -
this question has answer here:
- how parse , process html/xml in php? 27 answers
- regex match open tags except xhtml self-contained tags 35 answers
how safe match all <style>
blocks in body using preg_match_all()?
google not friend today.
$haystack = '<body> <style> .class { foo: bar; } </style> <p>hello world</p> <style> /* comment <p> */ .class > p { this: that; } </style> <p>some html</p> </body>'; preg_match_all('#<style>([^<]+)#is', $haystack, $matches, preg_set_order); var_dump($matches); preg_match_all('#<style>(.*)</style>#is', $haystack, $matches, preg_set_order); var_dump($matches);
did not work, matched < in style comment.
regular expression quantifiers greedy default, meaning match as possible. match few characters possible, change quantifier lazy (aka non-greedy) adding ?
after .*
following:
preg_match_all('#<style>(.*?)</style>#is', $haystack, $matches, preg_set_order);
you can read more greedy , lazy quantifiers here:
http://php.net/manual/en/regexp.reference.repetition.php
it's better use html parser regexp may not match html encounter. example, above regexp not work <style type="text/css">
. change regexp <style[^><]*>
it's better use html parser if can.
Comments
Post a Comment