Reputation: 311
This code works to allow only alphanumeric characters but I want to prevent $name
from starting with a number. How do I do this?
$name = "007_jamesbond";
if(preg_match('/[^a-z_\-0-9]/i', $name)){
echo "invalid name";
}
Upvotes: 0
Views: 1277
Reputation: 41810
It may be clearer to define a pattern for what is valid, and check for things that do not match it.
if(!preg_match('/^[a-z][a-z_\-0-9]*/i', $name)){
echo "invalid name";
}
// ^ anchor to beginning of string
// [a-z] a letter (add underscore here if it's ok too)
// [a-z_\-0-9]* any number of alphanumeric+underscore characters
Upvotes: 1
Reputation: 6386
Try this: (without using regex)
$first = substr($name, 0,1);
if(is_numeric($first))
{
echo 'the first character cannot be numeric';
}
else
{
if(preg_match('/[^a-z_\-0-9]/i', $name))
{
echo 'invalid name';
}
}
Upvotes: -1
Reputation: 10872
$name = "007_jamesbond";
if(preg_match('/^[^a-z]/i', $name)){
echo "invalid name";
}
The ^
at the start of a regex means "The start of the string". This regex can be read as: "If $name
starts (^
) with a character that is not a-z ([^a-z]
), it is invalid."
If you want a single regex to match both requirements ("only alphanum, doesn't start with non-letter"), you can use this:
/(^[^a-z]|[^\w\-])/
Upvotes: 0
Reputation: 23892
This should do it. Also \w
is alphanumeric characters and underscores.
$name = "007\_jamesbond";
if(preg_match('/(^\d|[^\-\w])/', $name)){
echo "invalid name";
}
Output:
invalid name
Regex101 Demo: https://regex101.com/r/dF0zQ1/1
Update
Should account for decimals and negative numbers as well...
$name = "007\_jamesbond";
if(preg_match('/(^[.\-]?\d|[^\-\w])/', $name)){
echo "invalid name";
}
Demo: https://regex101.com/r/dF0zQ1/2
Upvotes: 2