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

如何用PHP正则提取[button]自定义标签中的参数?

解决PHP提取自定义button标签参数的问题

你之前的正则匹配失败,是因为\w*只能匹配字母、数字和下划线,没法匹配#fff里的#符号,自然拿不到颜色值。下面给你两种可行的解决方案:

方案1:单独提取单个属性

如果只需要提取某一个属性,比如color,可以把正则改成匹配双引号内的所有非引号字符:

$text = '[button link="google.com" color="#fff" text="this text here"]';
// 提取color属性
preg_match('/color="([^"]+)"/i', $text, $color_match);
$color = $color_match[1] ?? ''; // 结果是#fff

// 同理提取link
preg_match('/link="([^"]+)"/i', $text, $link_match);
$link = $link_match[1] ?? ''; // 结果是google.com

// 提取text
preg_match('/text="([^"]+)"/i', $text, $text_match);
$button_text = $text_match[1] ?? ''; // 结果是this text here

方案2:一次性提取所有属性到关联数组

如果需要提取所有属性,用这个方法更高效:

$text = '[button link="google.com" color="#fff" text="this text here"]';
// 先匹配整个button标签内的属性部分
preg_match('/\[button\s+([^\]]+)\]/i', $text, $button_match);
if (!empty($button_match[1])) {
    // 匹配所有key="value"格式的属性对
    preg_match_all('/(\w+)="([^"]+)"/i', $button_match[1], $attr_matches);
    // 转成关联数组
    $button_attrs = array_combine($attr_matches[1], $attr_matches[2]);
    
    // 现在可以直接取变量
    $link = $button_attrs['link'] ?? '';
    $color = $button_attrs['color'] ?? '';
    $button_text = $button_attrs['text'] ?? '';
}

这种方式不管标签里有多少属性,都能一次性提取出来,后续扩展也方便。

内容的提问来源于stack exchange,提问作者Luiz Jr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:35:19