【问题标题】:Regex: get css classes,ids and tags正则表达式:获取 css 类、ID 和标签
【发布时间】:2014-05-26 15:40:15
【问题描述】:

我有获取 CSS 代码选择器的模式,它们是 .classes#idshtml 标签。我使用preg_match 将它们排序到一个数组中,只是选择器的名称。

发生的事情是我只得到了第一个选择器两次,一次带有打开的括号,另一次没有。

这是$contect

body{ color: black; } .class_class { color: #fff; font: tahoma; } #awesome_id{ }

这是结果:

Array
(
    [0] => body{
    [1] => body
)

这是代码:

<?php 
#Patterns
    $selectors  = "/(\.?\#?-?[_a-zA-Z]+[_a-zA-Z0-9-]*\s*)\{/";
#Sort
    preg_match($selectors, $content, $_selectors);
?>
<pre>
<?php
    print_r($_selectors);
?>
</pre>

我想要的-根据内容-结果是这样的

Array
(
    [0] => body
    [1] => .class_class
    [2] => #awesome_id
)

【问题讨论】:

  • 考虑使用 DOM 解析器。

标签: php html css regex


【解决方案1】:

你可以使用这个正则表达式~{(.*?)}~

<?php

$str='body{ color: black; } .class_class { color: #fff; font: tahoma; } #awesome_id{ }';
$str = preg_replace("~{(.*?)}~s","", $str);
$arr = array_filter(explode(' ',$str));
print_r($arr);

输出:

Array
(
    [0] => body
    [1] => .class_class
    [3] => #awesome_id
)

Demo

【讨论】:

  • 如果右括号和下一个选择器之间没有空格,这将不起作用。如果您将“”作为第二个参数放在 preg_replace 中,即使在这种情况下它也应该可以工作。
  • @Dexa,目前正则表达式正在按照 OP 的要求工作,如果您想修改,请随时编辑我的答案。 :)
  • 不,我不会编辑它,只是想提一下可以提供帮助的小东西。
  • 如果我的选择器之间有断线,那将不起作用。
  • @AbdullahSalma,我添加了s 修饰符,请参见代码。所以它也会匹配换行符。 $str = preg_replace("~{(.*?)}~s","", $str);
猜你喜欢
  • 2015-09-30
  • 2016-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-25
  • 2018-04-30
  • 1970-01-01
  • 2011-03-17
相关资源
最近更新 更多