好没问题。让我们分解一下:
\w+\s*=\s*
匹配一个字母数字关键字,后跟一个等号(可能被空格包围)。
"[^"]*"
匹配一个开始的双引号,后跟除另一个双引号之外的任意数量的字符,然后是一个(结束)双引号。
'[^']*'
对单引号字符串执行相同的操作。
将使用捕获组 ( (...)) 与简单的替换 ( |) 结合起来可以为您提供
(\w+)\s*=\s*("[^"]*"|'[^']*')
在 PHP 中:
preg_match_all('/(\w+)\s*=\s*("[^"]*"|\'[^\']*\')/', $subject, $result, PREG_SET_ORDER);
填充$result匹配数组。$result[n]将包含n第匹配的详细信息,其中
$result[n][0]是整场比赛
$result[n][1]包含关键字
$result[n][2]包含值(包括引号)
编辑:
要匹配不带引号的值部分,无论使用哪种引号,您都需要一个稍微复杂一些的正则表达式,它使用积极的前瞻断言:
(\w+)\s*=\s*(["'])((?:(?!\2).)*)\2
在 PHP 中:
preg_match_all('/(\w+)\s*=\s*(["\'])((?:(?!\2).)*)\2/', $subject, $result, PREG_SET_ORDER);
结果
$result[n][0]: 整场比赛
$result[n][1]: 关键字
$result[n][2]: 引号字符
$result[n][3]: 价值
解释:
(["']) # Match a quote (--> group 2)
( # Match and capture --> group 3...
(?: # the following regex:
(?!\2) # As long as the next character isn't the one in group 2,
. # match it (any character)
)* # any number of times.
) # End of capturing group 3
\2 # Then match the corresponding quote character.