Regexp for String_String? - php

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.

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
}

PHP preg_match regex to find letters numbers and spaces?

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)) ...

php filiter out special characters for userids and passwords

I would like to prevent new users from including apostophes, quotations and other special characters in their userids and passwords as I've found these can create unexpected problems down the road. Rather than anticipate every one of these problems, I'd rather just prohibit users from including those characters when signing up in the first place.
There are a lot of questions and stuff on the web in how to escape them to put them in the database but that is not the issue. I just want to throw an error msg that says enter something different.
I have tried:
$username = $_POST['username'];
if (preg_match ("/[&<>%\*\,\.\'\"]/i", $uid)) {
$strError="Your userid may not contain a special character. Please try again.";
}
but this is throwing an error No ending delimiter ''' found.
Would appreciate any suggestions.
Thanks.
I think you are going about this the wrong way. Instead of blacklisting special chars try whitelisting letters and digits e.g.
$username = $_POST['username'];
if (!preg_match('/^[\w\d]$/', $uid)) {
$strError="Your userid may not contain a special character. Please try again.";
}
to include asterisk and semicolon:
$username = $_POST['username'];
if (!preg_match('/^[\w\d\*;]$/', $uid)) {
$strError="Your userid may not contain a special character. Please try again.";
}
simplify it ...
<?php
$username = $_POST["username"];
if ( preg_match( "/^[A-Za-z0-9_]{3,20}$/", $username ) ) {
// username is valid
}
else {
// it contains special chars
}
?>
explaining regex...
"/^[
A-Z # any uppercase letters
a-z # any lowercase letters
0-9 # any digits
_ # underscore
]{3,20} # minimum 3 and maximum 20 characters
$/x"
The syntax highlighter shows you your obvious error: you have an extra ' on this line:
$username = $_POSt['username']';
should be
$username = $_POST['username'];
if (preg_match('/[^a-zA-Z]+/', $your_string, $matches))
{
echo 'Your userid may not contain a special character. Please try again.';
}
else
{
// No special characters found
}
may I suggest you not do that with preg_match ?
php has better functions for "sanitizing" strings - e.g. filter_var - check out FILTER_SANITIZE_STRING
I would suggest this snippet
$usernameRaw = trim($_POST['username']);
$username = filter_var( $usernameRaw , FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);

Php preg_match error message

I want to match a string using REGEX which follows the syntax:
Text/number
So my preg_match() function is...
if(preg_match("/[^A-Za-z/0-9]$/ ", $folio))
$err[] = "Wrong value, it's should be lik: C/455";
But getting error message...
Try this:
$folio = "Text/15";
if(preg_match('~[a-z]/[\d]~i', $folio))
echo "match";
else
echo "no match";
You needed to escape / using \. Also numbers is a subset of text and you need to include it in your text part. You need one or more text/numeric characters, so a + is required.
It adds up to the following statement:
if(preg_match("/^[A-Za-z0-9]+\/[0-9]+$/", $folio))
You either need to escape / or use different char to surround regexp, for example:
if(preg_match("#[^A-Za-z/0-9]$# ", $folio))
if ( ! preg_match('/\b[a-z]+\/[0-9]+\b/i', $folio)) {
$err[] = "Wrong value, it's should be like this: C/455";
}

Categories