php - How to preg_match all style tags? -


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

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -