PHP preg_match regex to find letters numbers and spaces? - php

When people sign up to my site I validate their names with this code:
if (preg_match("[\W]", $name))
{
$mess = $mess . "Your name must contain letters only.<br>";
$status = "NOTOK";
}
This is because your actual name cannot contain symbols unless your parents were drunk when they named you.
However, this regex doesn't detect spaces. How can I fix it?

You can use the following regular expression:
^[\w ]+$
This matches any combinations of word characters \w and spaces , but as the guys said be careful because some names might contain other symbols.
So you can use it like this:
if (preg_match("/^[\\w ]+$/", $name)) {
// valid name
}
else {
// invalid name
}

Try this:
<?php
$user_input = 'User_name';
if (!preg_match('/^[a-z0-9_\s]+$/i', $user_input)) {
// Matches English letters, numbers underscores(_) and spaces
$mess = $mess . "Your name must contain letters only.<br>";
$status = "NOTOK";
}
?>

You just missed regexp separators. I do this sometimes even after 10 years of programming.
if (preg_match("/[\W]/", $name)) ...

Related

Prevent a number from being the first character in a string with preg_match()

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";
}
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
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
$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\-])/
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';
}
}

Preg match and Preg replace specific format

I need help with preg match/replace forma i really cant understand how its working and what each element doing.
So far I have this:
$username = preg_replace('/\s+/', '_', $_POST['uname']);
if(preg_match('/^[a-zA-Z0-9]{5,12}+$/u', $username))
{
$username = trim(strip_tags(ucfirst($purifier->purify(#$_POST["uname"]))));
}
else
{
$message['uname']='wrong username input';
}
And for utf8(hebrew language) i got this:
if(preg_match("/^[\p{Hebrew} a-zA-Z0-9]{2,10}+$/u", $_POST['fname']))
{
//
}
which is working perfect, but I don't want to allow Hebrew on username just English.
I tried to play with that in multiple combinations, I tried to change but no success, and I did research on StackOverflow and Google but can't make it like I want I don't understand.
I used a RegEx site to and tried to build but with no success.
So until now I got this :
User can put 5-12 letters/numbers no special characters.
What i want is :
Can enter between 5-12 letters/numbers no special charcaters - i
already have it.
Allow whitespaces
preg_match if no mixed language's like E.G: $username = שדגדשsdsd; <- not allowed mixed languages.
And preg_replace to:
Replace white spaces to nothing (remove white spaces) i have this but i dont know if it correct:
$username = preg_replace('/\s+/', '', $_POST['uname']);
Also, I am using UTF-8 language .
EDIT:
With help of hwnd , i make it to work like i want the latest code:
if(preg_match('/^[\p{Hebrew}]{2,10}|[a-zA-Z]{2,10}$/u', $_POST['fname']) && preg_match('/^[a-zA-Z]{2,10}|[\p{Hebrew}]{2,10}$/u', $_POST['fname']))
{
$message = 'valid';
}else{
$message = 'Invalid';
}
Solved,Thanks.
I'm sure if your allowing whitespace in the username, you can suffice with just a space character but to be safe use \s which matches whitespace (\n, \r, \t, \f, and " "), for that you can just add that inside of your character class []
if (preg_match('/^[a-zA-Z0-9\s]{5,12}+$/u', $username)) { ...
And you can leave your preg_replace() function as is...
Update: To match different characters, but not mixed you could try the following:
$user = 'hwדגדשרביd'; // "invalid"
$user = 'fooo'; // "valid"
$user = 'שדגדשרביב'; // "valid"
if (preg_match('/^[\p{Hebrew}]{2,10}|[a-zA-Z]{2,10}$/u', $user)) {
echo "valid";
} else {
echo "invalid";
}
Your preg_replace for removing whitespace from the username is fine.
To allow only English letters, digits and whitespace in the username, use this:
if (preg_match('/^[a-zA-Z0-9\s]{5,12}+$/u', $username)) {
# $username is OK
}
else {
# $username is not OK
}

Regexp for String_String?

I'm pretty stupid to regexp but I have to use this... I have to validate a username field that must match to this scheme: "Firstname_Lastname"
This means that the valid username is only alphabet separated by an underscore. The first name and the last name must start with uppercase but the rest of them must be lowercase.
I have tried this but it's not working:
<?php
$username = "Dani_Sebi";
$regex = '/^[A-Z][a-z]+_^[A-Z][a-z]+/';
if (preg_match($regex, $username)) {
echo $username . " is a valid username. We can accept it.";
} else {
echo $username . " is an invalid username. Please try again.";
}
?>
^ is misplaced inside the reex. Try this:
$regex = '/^([A-Z][a-z]+)_([A-Z][a-z]+)/';
I bet this could be improved, but it works:
^[A-Z][a-z]+_[A-Z][a-z]+$
^[:upper:][:lower:]*_[:upper:][:lower:]*$
There are single letter names as well, so this one is better.

Check text box for spaces

I need help with code to output an error if a text box contains a space or hyphen. I have the following:
elseif($_REQUEST['students']['FIRST_NAME']!= "CONTAINS SPACE OR HYPHENS")
{
$insert_error = 'No spaces, hyphens, or spaces allowed in first name';
}
What function could I use? I have other functions that work for similar tasks such as:
elseif($_REQUEST['students']['PASSWORD']!=$_REQUEST['verify_password'])
{
$insert_error = 'Passwords did not match.';
}
I know it's quite straight forward, but I'm not sure what to use. Forgive me, I'm very rusty.
Use regular expressions and the preg_match() function.
if ( preg_match('/[\s-]/', $_REQUEST['students']['FIRST_NAME']) ) {
$insert_error = 'You cannot enter spaces or dashes';
}
The [\s-] inside of preg_match() is called a regular expression. The \s is for any whitespace character, and the - is for the dash.
More information here: http://php.net/manual/en/function.preg-match.php
$first_name = $_REQUEST['students']['FIRST_NAME'];
elseif((preg_match("/\\s/", $first_name) === true)
")
{
$insert_error = 'No spaces, hyphens, or spaces allowed in first name';
}

RegEx to validate usernames

I am not very good in Regular Expression, and can't seem to understand them quite well.
I am looking for a regular expression which will match and allow following strings for a username, with these conditions:
username can: start with a number or with a alphabetic letter
username can contain special chars: dots, dashes, underscores
username must be in this range: from 3 chars up to 32 chars.
alphanumeric characters in the username can be both: lowercase and uppercase
cannot contain empty spaces
Almost similar to Twitter's and Facebook username patterns.
Please help me. Thank you.
FWI: I have tried this: /^(?=.{1,15}$)[a-zA-Z][a-zA-Z0-9]*(?: [a-zA-Z0-9]+)*$/ - and this does not satisfy my conditions.
Try this one
^[a-zA-Z0-9][a-zA-Z0-9\._-]{2,31}$
this results in the php code
if (preg_match('~^[a-zA-Z0-9][a-zA-Z0-9\._-]{2,31}$~', $username) {
//do something
}
Starts with digit or alphabetic
[a-zA-Z0-9]
can contain as above plus dots, dashes and underscores
[a-zA-Z0-9._-]
and all together
[a-zA-Z0-9][a-zA-Z0-9._-]{2, 31}
try this one this is working for me in every registration form
//username Validation
var usernameRegex = /^[a-zA-Z0-9\s\[\]\.\-#']*$/i;
var username=document.getElementById('username');
if(username.value==""){
document.getElementById('lblusername').innerHTML="Username Required!";
username.focus();
return false;
}
else if(usernameRegex.test(username.value)== false)
{
document.getElementById('lblusername').innerHTML="Allow Alphanumeric Only! (E.g Demo123)";
username.focus();
return false;
}
else
{
document.getElementById('lblusername').innerHTML="";
}
Try this:
^[0-9a-zA-Z][0-9a-zA-Z\-\._]{2,31}$

Categories