使用正则表达式从CSS属性返回CSS值


Return the CSS values from CSS attributes using regex

我有以下正则表达式:

$string = 'font-size:12em;';
$pattern = '@:[A-Za-z0-9.]+;@i';
preg_match($pattern, $string, $matches);

$matches返回:

Array ( [0] => :12em; )

但是,为什么会返回:; ?我怎么能让它不返回那些冒号,只返回CSS值12em ?

因为数组中的第一个元素是整个匹配。使用捕获组和第二个元素(或使用查找)。

的例子:

preg_match('/:'s*('w[^;}]*?)'s*[;}]/', $string, $matches);
print $matches[1];

请注意,这样的事情并不是在所有情况下都有效。注释和更复杂的语句可能会破坏它。

的例子:

/* foo: bar; */
foo: url("bar?q=:x;");

使用以下模式:

@(?<=:)[A-Za-z0-9.]+(?=;)@i

解释是(?<=)(?=)分别是向后看组和向前看组。这意味着它们不会作为匹配的一部分被捕获。


编辑处理% +more

@(?<=:)[^;]+@i