View Full Version : A little bit of regex

02-20-2008, 01: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?

02-20-2008, 03: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 );

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

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


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?

02-20-2008, 04: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.

02-20-2008, 05: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';
echo 'bad';

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

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

Is that OK?

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