...

View Full Version : A little bit of regex



Jacka
02-20-2008, 12:31 PM
I have an input that is only allowed to contain alphanumeric characters and spaces, but no symbols.

My current regex is shown below, but does always return true if there is atleast one alphanumeric present at the beginning.



preg_match("#^[A-Za-z0-9\s]#", $input)


Any ideas on how this can be achieved?

kbluhm
02-20-2008, 02:30 PM
Rather than use a RegExp, try the ctype library (http://www.php.net/ctype).

Since you only want alphanumeric characters and spaces... I'd strip out all spaces first. At that point, you should only be left with alphanumeric characters if the original string was formatted properly. You can then use ctype_alnum() to check this.

Give this a shot:


function alnum_and_spaces( $string )
{
$string = str_replace( ' ', '', $string );
return ctype_alnum( $string );
}

Jacka
02-20-2008, 02:42 PM
Perfect, thank you very much.

Jacka
02-20-2008, 03:13 PM
I need a bit more help.



Removed


With the both ctype that you suggested and the regex, it works fine unless there is a space.

Is there any way to allow spaces in the input?

Jacka
02-20-2008, 03:17 PM
Wait a minute, I just realised that I can removed spaces and check for the presence of symbols, then just use the original input!

Thank you again kbluhm.

kbluhm
02-20-2008, 04:40 PM
Yeah, just use the function I gave you. It won't change the original input value:


$_POST['input'] = 'This is alphanumeric and spaces only'; // sent from form input

if ( alnum_and_spaces( $_POST['input'] ) )
{
echo 'good';
}
else
{
echo 'bad';
}

Jacka
02-20-2008, 04:53 PM
<?php
$input = ucwords(strtolower(str_replace(array("_", "-"), " ", $_POST['input'])));

if(ctype_alnum(str_replace(" ", "", $input)) && strlen($input) <= 12){
echo "{$input} added to $table in $db";
}
else{
echo "Invalid input";
}
?>


Is that OK?

kbluhm
02-20-2008, 05:01 PM
Looks like it will work.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum