thiesdiggity
thiesdiggity

Reputation: 1967

Regular Expression to get the size value of a CSS property?

I wrote a regular expression to get the size from a CSS property:

/(([+-]?\d*\.?\d+(\s)*(px|em|ex|pt|in|pc|mm|cm)?)|thin|medium|thick)(\s|;|$)/i

but for some reason its not working as intended. For example, when I run the following:

preg_match_all('/(([+-]?\d*\.?\d+(\s)*(px|em|ex|pt|in|pc|mm|cm)?)|thin|medium|thick)(\s|;|$)/i', 
"border-bottom:1px solid #99999;", $matches);

It outputs:

1px
99999;

But I only want the 1px value returned.

I understand why its returning the above but can't seem to figure out how to only return the size and not the color value. I tried using the following negative lookbehind but it's not working either:

/(((?<!#\d{3}|#\d{6})[+-]?\d*\.?\d+(\s)*(px|em|ex|pt|in|pc|mm|cm)?)|thin|medium|thick)(\s|;|$)/i

I want to use preg_match_all for those CSS properties that can have multiple size values (i.e. margin).

Anyone have any ideas how to get this regex to return only the size values?

Thanks for your help!

Upvotes: 1

Views: 1066

Answers (2)

thiesdiggity
thiesdiggity

Reputation: 1967

OK, so 5 minutes after I asked this question I figured it out. Use a positive lookbehind and check for a " " or a semicolon.

'/((?<=\s|:)([+-]?\d*\.?\d+(\s)*(px|em|ex|pt|in|pc|mm|cm)?)|thin|medium|thick)(\s|;|$)/i'

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167212

Why don't you try removing the #\d{3}|#\d{6} in your regexp and try?

preg_match_all('/(([+-]?\d*\.?\d+(\s)*(px|em|ex|pt|in|pc|mm|cm)?)|thin|medium|thick)(\s|;|$)/i', "border-bottom:1px solid #99999;", $matches);

Upvotes: 0

Related Questions