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!';
}
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]+$/'