Abs
Abs

Reputation: 57916

Return the CSS values from CSS attributes using regex

I have the following regex:

$string = 'font-size:12em;';

$pattern = '@:[A-Za-z0-9.]+;@i';

preg_match($pattern, $string, $matches);

$matches returns:

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

However, why is the : and ; returned? How can I get it to not return those colons and only return the CSS value 12em?

Upvotes: 0

Views: 87

Answers (2)

Jacob Eggers
Jacob Eggers

Reputation: 9322

Use this pattern instead:

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

The explanation is that you the (?<=) and (?=) are respectively lookbehind and lookahead groups. Which means they aren't captured as part of your match.


Edit For handling %'s +more

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

Upvotes: 0

Qtax
Qtax

Reputation: 33908

Because the first element in that array is the whole match. Use a capturing group, and the second element (or use lookarounds).

Example:

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

Note that things like these will not work in all cases. Comments and more complicated statements could break it.

Example:

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

Upvotes: 1

Related Questions