You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP的preg_match_all匹配含Rubik的CSS代码块?

解决PHP正则匹配含特定内容的CSS代码块问题

我来帮你搞定这个正则匹配的需求!你需要从给定的CSS字符串里提取所有包含Rubik的完整代码块(从{到对应的}),用preg_match_all实现,对吧?

解决方案

这里给你一个精准的正则表达式,再配合完整的PHP代码示例:

首先是核心正则表达式:

/{[^{}]*Rubik[^{}]*}/

然后是可直接运行的PHP代码:

$str = "#button_1589817804107 .omw-custombutton button {font-family:Rubik !important; font-weight:normal !important; font-style:normal !important;} #button_1589817804307 .omw-custombutton button {color:red} #button_1589817804407 .omw-custombutton button {font-family:Rubik; font-weight:300 !important; font-style:italic !important;}";

// 定义正则匹配模式
$pattern = '/\{[^{}]*Rubik[^{}]*}/';
// 执行全局匹配
preg_match_all($pattern, $str, $matches);

// 输出匹配结果
print_r($matches[0]);

正则表达式拆解

让我把这个正则的每个部分解释清楚,帮你理解它的工作逻辑:

  • \{:转义匹配左大括号{(因为{在正则里是特殊元字符,必须转义才能匹配字面量)
  • [^{}]*:匹配任意数量非大括号的字符,这一步能确保我们不会跨到其他CSS代码块中
  • Rubik:精准匹配你要定位的目标字符串
  • [^{}]*:再次匹配任意数量非大括号字符,直到当前代码块的结束大括号
  • \}:转义匹配右大括号}

结果验证

运行上述代码后,你会得到完全符合预期的匹配数组:

Array
(
    [0] => {font-family:Rubik !important; font-weight:normal !important; font-style:normal !important;}
    [1] => {font-family:Rubik; font-weight:300 !important; font-style:italic !important;}
)

这个方案适用于常规CSS声明块(无嵌套大括号的场景),刚好匹配你给出的需求。如果之后遇到包含嵌套大括号的复杂CSS,我们再调整正则逻辑即可~

内容的提问来源于stack exchange,提问作者Bruno Braga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:07:37