...

View Full Version : Preg Match Help



Scriptet
10-28-2009, 03:50 PM
Hi,

I need to use a preg match to check if a color entered is a valid hexidecminal color. I found the following off a website:



if(preg_match('/^#[a-f0-9]{6}$/i', $color)) //hex color is valid
{

}


This works great, but a hex color can also be 3 characters, and the preg match in question does not allow for this.

I have no idea how preg-matches work or how easy they are to code, but can this be amended to allow for 3 characters also?

Lamped
10-28-2009, 03:54 PM
'/^#[a-f0-9]{6}$|^#[a-f0-9]{3}$/i'

| means OR.

Scriptet
10-28-2009, 04:00 PM
Thanks ComputerX for the quick, and effective reply!!

If anybody has a great tutorial on learning about preg matches please do post...because I need to learn this for myself also.

For instance I now need to write one which checks if the field is in the form 200px or 200%, obviously the 200 can be any number, but have no idea on how to go about it.

Phil Jackson
10-28-2009, 04:39 PM
preg_patch("#^([0-9]*)((?:%)|(?:px))$#is", $str, $array);

$array[1] = number value
$array[2] = px | %

^ = begging of string
$ = end of string

("this size is 200px!") return false
("200px!") return false
("!200px") return false
("200px") return true

() group together and access value from array
(?:) group together but leave out from accessible array
| means or
[] means either
[0-9] figure between 0 and 9
* means 0 or more times

EDIT: use of + would be more appropriate
preg_patch("#^([0-9]+)((?:%)|(?:px))$#is", $str, $array);

+ means one or more times



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum