PHP - Help writing regex?
I am trying to pick up regex using nettuts. However I still haven't got very far and something need's fixing today.
I need a regex that does the following.
$html = '...'; // Lots of HTML
$regex = '{absolutely anything}color: #{6 digits - [0-9][a-f][A-F]};{absolutely anything}';
I will then use this to force users to have a certain color on their HTML elements.
Would an开发者_Python百科yone mind converting the $regex variable to actual regex?
You're pretty close.
/color:\s*\#[A-Fa-f0-9]{6};/
If you want "absolutely anything" then... don't add anything else! You can use quantificator and classes for the rest :
$regex = '/color: #[a-fA-F0-9]{6};/'
[a-fA-F0-9] matches any character between a-f (lowercase), A-F (uppercase) and a digit. {6} means it must has exactly 6 characters.
Don't forget that with PHP's PCRE extension, you need delimiters (/) in this case).
/color: ?#([0-9a-f]{3}){1,2};/i
Features:
- Optional whitespace between
color:
and value #rgb
and#rrggbb
matching
Furthermore, you might want to add a [^-]
part in order not to match background-color: #...
: /[^-]color: ?#([0-9a-f]{3}){1,2};/i
. Also, you could use a negative lookbehind if you so desire: (?<!-)
.
精彩评论