0

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?

2 Answers 2

1

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;");
Sign up to request clarification or add additional context in comments.

2 Comments

That is a good point, all I am looking for really is the CSS values ending in em and px - maybe I should use these to narrow things down? How would you implement this in your regex?
@Abs, try /:\s*(\w[^;}]*?(?:em|px))\s*[;}]/
0

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

1 Comment

That works well. However, when I try it on width:10% it doesn't seem to return any value? Maybe the % is a special character?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.