【问题标题】:php regex to get strings that start with any character and end with open bracephp regex 获取以任何字符开头并以左大括号结尾的字符串
【发布时间】:2017-02-14 06:33:34
【问题描述】:

我有试图使用 php 操作的 css 文件。所以如果我的 css 是这样的......

.something {
    display:none;
    background: blue;
}

.somethingElse {
    display:block;
}

我希望能够得到一个类名数组。所以我的数组看起来像......

['.something', '.somethingElse']

这是我的尝试($homepage 是我的 css 文件)...

$homepage = file_get_contents("style.css");
$regex = '/[\s\S]\K[^{]*(?=})/m';
preg_match_all($regex, $homepage, $matches);

我试图做的是找到所有以任何字符开头并以左大括号{ 结尾的字符串。我的正则表达式都错了,正确的方法是什么?

【问题讨论】:

  • 试试'~^\h*\.([^\n{]*?)\s*{~m'。要解析任意 CSS,请使用 CSS 解析器。见Parse a CSS file with PHP
  • 我认为使用 PHP 编写的 CSS 解析器会更好。
  • 一个 CSS 块的多个类名怎么样?如果它们之间有 id 名称或其他不同的选择器怎么办?

标签: php regex


【解决方案1】:

这应该很好用:

\.([\w]+)\s*{

类名在 #1 组中。

例子:

preg_match_all("/\.([\w]+)\s*{/", $homepage, $matches);

【讨论】:

    猜你喜欢
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多