Log in

View Full Version : Some Regex Help?



alexjewell
10-17-2007, 09:06 PM
I'm trying to check to make sure a variable equals something like the following:

(number)(possible number)(possible number).jpg

So, for example: 1.jpg would work, 20.jpg would work, 101.jpg would work...but 10000.jpg or something.txt wouldn't work.

Here's my code, which is returning the following error:



if(preg_match('^[1-9][1-9]?[1-9]?\(.jpg)$',$src)){ echo "yeah!";} else{ echo "no!";}




Warning: preg_match(): No ending delimiter '^' found in /home/content/a/l/e/alexjewell/html/clients/quinn/regexImg.php on line 5


Any ideas?
Thanks

boogyman
10-17-2007, 09:12 PM
you forgot the forward slashs ( / )


if( preg_match("/^\d{1,3}(.jpg)$/", $src) ) ? echo "yeah!" : echo "no!";

\d = digit quantifier
{1,3} = must be at least 1 digit and cannot be any more then 3 digits

Twey
10-17-2007, 09:19 PM
And you forgot to escape the dot and misused the ternery conditional operator:
echo preg_match('/^\d{1,3}\.jpg$/', $src) ? 'yeah!' : 'no!';

alexjewell
10-17-2007, 09:36 PM
Thanks guys - I'm still learning regex. :)

Oh, and I have no idea how the if got in there. :/

Twey
10-17-2007, 10:32 PM
Your if was correct, boogyman's wasn't.

A breakdown of the expression:
'A lot of regex characters are also special characters in PHP. Using single-quoted strings means we don't have to worry about escaping them, as well as being slightly more efficient.
/This means "start regular expression." Whatever you use here must be escaped within the expression proper, and you can use one of several different characters instead, such as # or ^, if this is easier for your expression. Then the expression says to
^directly after the start of the the string, find
\da digit
{1,3}repeated between one and three times, followed by
\.jpgthe literal string .jpg (the dot has to be escaped since it's a special character that means "any character" in regex) and then
$the end of the string.
/End regex.

boogyman
10-18-2007, 12:49 AM
And you forgot to escape the dot and misused the ternery conditional operator:
echo preg_match('/^\d{1,3}\.jpg$/', $src) ? 'yeah!' : 'no!';

bah I knew something looked off. I probably should start testing my solutions before providing them, would stop alot of these lil errors :|