Page 1 of 1

regular expressions

Posted: Sun Feb 20, 2005 2:47 pm
by dannymc1983
does anyone know what the regular expression for the following are:
1) a string that contains only the digits 0-9, can contain only 7 digits (no more, no less) and cannot contain spaces
2) a stirng that contains only characters a-z, both uppercase and lowercase and can contain spaces. ie. it is a stirng used for storing a name

Posted: Sun Feb 20, 2005 2:54 pm
by feyd

Code: Select all

preg_match('#^ї0-9]{7}$#', $text1);
preg_match('#^їA-Z ]$#i', $text2);

Posted: Sun Feb 20, 2005 2:58 pm
by neophyte
1) a string that contains only the digits 0-9, can contain only 7 digits (no more, no less) and cannot contain spaces

#^[0-9]{7}$#
2) a stirng that contains only characters a-z, both uppercase and lowercase and can contain spaces. ie. it is a stirng used for storing a name
#^[a-zA-Z ]$#

Warning I'm a regex noob. So test these.

Feyd will probably answer this post before I ever hit submit...

Is that right Feyd?

Posted: Sun Feb 20, 2005 3:02 pm
by feyd
tooo slow.. :P

Posted: Sun Feb 20, 2005 4:38 pm
by dannymc1983
hey feyd
thanks for reply
1st reg expression runs ok
2nd reg expression (to identify names, ie upper and lowercase letters only, spaces allowed) doesnt seem to be working. this example has your regular expression, see what happens when you run it:

<?
$name = "Danny";

if (!preg_match('#^[a-zA-Z]$#i', $name))
echo "invalid";
else
echo "valid";

?>

Posted: Sun Feb 20, 2005 4:41 pm
by feyd
oops.. my brain was off..

Code: Select all

#^&#1111;A-Z ]+$#

Posted: Sun Feb 20, 2005 4:57 pm
by dannymc1983
ok its working now, kind of......
only thing it wont accept is a name with spaces, like the following example:

<?

$name = "mc donald";

if (!preg_match('#^[a-zA-Z]+$#', $name))
echo "invalid";
else
echo "valid";


?>

Posted: Sun Feb 20, 2005 5:00 pm
by feyd
look at my post again...

Posted: Sun Feb 20, 2005 5:02 pm
by dannymc1983
:oops:
missed that!
thanks

Posted: Sun Feb 20, 2005 7:02 pm
by dannymc1983
just one last thing, how would i incorporate a ' into the regular expression
to allow for names like o'donnell.

Posted: Sun Feb 20, 2005 7:06 pm
by Chris Corbyn
Just add a backslash floowed by a single quote in the square brackets... dude, all you're doing is specifying the permitted characters ;-)

Code: Select all

#^&#1111;A-Z'' ]+$#i