Log in

View Full Version : Regex Help



fileserverdirect
01-24-2010, 09:54 PM
Hello, I can't seem to come up with a regular expression that will check to see if there are both letters AND numbers. I could only make it so it would check if it was Alphanumeric, but how can I make it so it will only return if BOTH letters and numbers are present:

if(preg('[A-Za-z0-9]', $string))$message = "Alphanumeric";
echo $message;

The above string will output if $string="123"; or $string="abc";. But I onlywant it to output if $string="abc123";
What is the correct Regular Expression for this?
Thanks,

djr33
01-24-2010, 09:57 PM
I'm not sure, but you could split the string in two and check them independently.

fileserverdirect
01-24-2010, 10:31 PM
I'm not sure what you mean, can you elaborate on how to do it. would you search the string for numbers and then search it for letters?

djr33
01-24-2010, 10:40 PM
$string = 'aaa111';
$s1 = substr($string,0,3);
$s2 = substr($string,3);
//$s1 = alpha
//$s = numeric
//also, strlen($s1) and strlen($s2) should == 3

fileserverdirect
01-24-2010, 11:32 PM
I guess I was not entirely clear, the $string will be mixed numbers\letters like "1z3" or "98j" or "xy5" so I don't know where the letters\numbers are located in the string. I'm figuring I have to use two regular expressions on the string to pull out the letters and then the numbers. Then I have to check to see if these new strings are not null.
----
AHAH! I think I solved it, haven't fully tested it yet but:


$alpha=preg('[^A-Za-z]', $string);
$numeric=preg('[^0-9]', $string);
if(!$alpha || !$numeric) $message="This string has numbers and variables";

This works, but I wonder if there is any other function or regular express that will simplify this....

bluewalrus
01-25-2010, 12:35 AM
if (preg_match('/\d/', $alpha_num) && (preg_match('/[a-zA-Z]/', $alpha_num))) {


A full example



<form method="post" action="">
<input type="text" name="alphanum" />
<input type="submit" />
</form>
<?php
if (isset($_POST['alphanum'])) {
$alpha_num = $_POST['alphanum'];
echo $alpha_num . "<br />";
if (preg_match('/\d/', $alpha_num) && (preg_match('/[a-zA-Z]/', $alpha_num))) {
echo "alpha numeric";
} else {
echo "not";
}
}
?>