PHP - Help write a regex?

I am trying to find a regex using nettuts . However, I am still not very far away, and today I need to fix something.

I need a regex that does the following.

$html = '...'; // Lots of HTML $regex = '{absolutely anything}color: #{6 digits - [0-9][af][AF]};{absolutely anything}'; 

Then I use this to make users have a specific color in their HTML elements.

Could anyone convert the $ regex variable to the current regex?

+4
source share
3 answers

If you want "absolutely nothing," then ... do not add anything! You can use the quantifier and classes for the rest:

 $regex = '/color: #[a-fA-F0-9]{6};/' 

[a-fA-F0-9] matches any character between af ​​(lowercase), AF (uppercase) and a digit. {6} means that it must have exactly 6 characters.
Do not forget that with the PHP PCRE extension you need delimiters (/) in this case).

+2
source

You are pretty close.

 /color:\s*\#[A-Fa-f0-9]{6};/ 
+3
source
 /color: ?#([0-9a-f]{3}){1,2};/i 

Features:

  • Additional spaces between color: and value
  • #rgb and #rrggbb matching

Alternatively, you can add the [^-] part to not match the background-color: #... : /[^-]color: ?#([0-9a-f]{3}){1,2};/i . Alternatively, you can use negative lookbehind if you want: (?<!-) .

+2
source

All Articles