【问题标题】:php regular expression preg_match get css classes,ids and tagsphp 正则表达式 preg_match 获取 css 类、ID 和标签
【发布时间】:2015-09-30 02:39:07
【问题描述】:

我有以下css代码

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);

【问题讨论】:

标签: php css regex preg-replace preg-match


【解决方案1】:

您可以使用此代码:

$re = '/.*\bimg\b.*?{(?s:.*?)}/i'; 
$str = "thead \n{\n    /*some code*/\n}\ntr,img {\n    /*some code*/\n}\n@page {\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

解释:

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

【讨论】:

    猜你喜欢
    • 2014-05-26
    • 2013-04-05
    • 2014-06-28
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多