2015-07-11 95 views
0

我有以下的CSS代码PHP正则表达式的preg_match得到CSS类,id和标签

thead 
{ 
    /*some code*/ 
} 
tr,img { 
    /*some code*/ 
} 
@page { 
    /*some code*/ 
} 
p,h2,h3 { 
    /*some code*/ 
} 
h2,h3 { 
    /*some code*/ 
} 
img { 
    /*some code*/ 
} 

我想与使用PHP正则表达式的preg_match或preg_replace函数图片IMG CSS。 例如,如果我寻找IMG,以下输出将必须表明

tr,img { 
    /*some code*/ 
} 
img { 
    /*some code*/ 
} 

PHP代码是

$str='img{ } .class_class { } #awesome_id{ }'; 
$search='img'; 
$str = preg_replace("~{(."$search".)}~s","", $str); 
$arr = array_filter(explode(' ',$str)); 
print_r($arr); 
+2

你能否提供你已经在问题中做出的尝试? –

+0

我加了php代码。 –

+0

如果没有[嵌套{}](http://programmers.stackexchange.com/a/23241/126902),请使用[preg_match_all]尝试[像这样](https://regex101.com/r/rK1xJ5/1) ](http://php.net/manual/en/function.preg-match-all.php)函数。 –

回答

0

您可以使用此代码:

$re = '/.*\bimg\b.*?{(?s:.*?)}/i'; 
$str = "thead \n{\n /*some code*/\n}\ntr,img {\n /*some code*/\n}\[email protected] {\n /*some code*/\n}\np,h2,h3 {\n /*some code*/\n}\nh2,h3 {\n /*some code*/\n}\nimg {\n /*some code*/\n}"; 
preg_match_all($re, $str, $matches); 

这里是一个regex demo

说明:

  • .* - 字面整个字img(不区分大小写由于i标志)
  • .*? - - 任何字符,但换行符,0的任何字符,但一个新行,0次或多次匹配之前
  • \bimg\b或以上,但尽可能少
  • { - 字面{
  • (?s:.*?) - 任何字符甚至换行符(由于(?s:)内联标志)但尽可能少
  • } - 文字}