Simple Preg_match question

If there is such a thing. I am just trying to validate a username contains only numbers and letters and has no spaces. I tried the one below but it always returns true even with a space in the value. In the expression below, am I asking if it contains one or more of the letters and numbers? What I really want to be asking is does it include only letters and numbers.

$username = 'user 1';
$regex = '/[0-9a-zA-Z]+/';

if (preg_match($regex, $username) == 1) {
	echo 'Username '.$username.' is valid!';
} else {
	echo 'Username '.$username.' is invalid!';
}

I just found the ctype_alnum function that should actually give me what I want. However, can I do what I want with regular expressions?

Yes you could but using built in functions where such functions exist is better as then you know it will work - there is always a possibility that a regular expression doesn’t do quite what you expect or possibly contains a typo and so you should only use regular expressions for validation where a built in function or filter for what you want doesn’t exist.

The regular expression you are after in this instance would be '/^[0-9a-zA-Z]+$/'

Thanks for the input. I see exactly what I was doing wrong. But will use the ctype functions first as advised. Cheers

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.