I have following css code
thead
{
/*some code*/
}
tr,img {
/*some code*/
}
@page {
/*some code*/
}
p,h2,h3 {
/*some code*/
}
h2,h3 {
/*some code*/
}
img {
/*some code*/
}
I want all css related to img using php regular expression preg_match or preg_replace. For example if I searched for img, following output will have to show
tr,img {
/*some code*/
}
img {
/*some code*/
}
php code is
$str='img{ } .class_class { } #awesome_id{ }';
$search='img';
$str = preg_replace("~{(."$search".)}~s","", $str);
$arr = array_filter(explode(' ',$str));
print_r($arr);
You can use this code:
$re = '/.*\bimg\b.*?{(?s:.*?)}/i';
$str = "thead
{
/*some code*/
}
tr,img {
/*some code*/
}
@page {
/*some code*/
}
p,h2,h3 {
/*some code*/
}
h2,h3 {
/*some code*/
}
img {
/*some code*/
}";
preg_match_all($re, $str, $matches);
Here is a regex demo
Explanation:
.*
- matches any characters but a newline, 0 or more times before\bimg\b
- a literal whole word img
(case-insensitively due to i
flag).*?
- any characters but a newline, 0 or more but as few as possible{
- a literal {
(?s:.*?)
- any character even a newline (due to (?s:)
inline flag) but as few as possible}
- Literal }
.