Can Anyone help me out with regular expression in PHP - php

I dont have much knowledge on Regular expression. Help me out if i could achieve the below,
Username must need to validate this.
Only contains alphanumeric characters, underscore and dot
Underscore and dot can't be at the end or start of a username
Underscore and dot can't be next to each other
Underscore or dot can't be used multiple times in a row
I have come up with this regular expression but i cant fulfill all the above.
/(?<![a-z_|.])([a-z](?:[a-z]|_|.(?!_.))+[a-z]|[a-z]{2})(?![a-z_|.])/
Thanks in advance.

You don't need any lookbehind. Simplify your regex to this:
/^[a-zA-Z0-9](?!(?:.*\.){2}|(?:.*_){2}|.*[._]{2})[a-zA-Z0-9_.]*[a-zA-Z0-9]$/
RegEx Demo

One way to rome... (simple and easy version)
if(substr_count($string,'_')<=1 //for rule 4.
&& substr_count($string,'.')<=1 //for rule 4.
&& substr_count($string,'._')===0 //for rule 3.
&& substr_count($string,'_.')===0 //for rule 3.
&& preg_match('/^[^_\.][a-zA-Z]+[^_\.]$/',$string)// for rule 1. & 2.
) {
echo 'Valid';
}

Related

Regular expression with optional |

I have the next code and I'm trying to know if the string its valid based on the regular expression.
I'm trying to validate only strings that follow the next sequence.
lettersOrNumbersAndunderDashes=lettersOrNumbersAndUnderdashes
But that sequence can be repeated if there is a vertical bar.
For example parameter1=value1|parameter2=value2|parameterN=valueN
if (preg_match("/((^[A-Za-z0-9_]+=[A-Za-z0-9_]+)\|?)/m", "perPd_asd=as_3_4d|asdas=asdasd"))
return 'Valid';
return 'Invalid';
I think I'm missing something or building a wrong regular expression.
The wrong thing you did is putting a ^ at the beginning of the pattern, which means that it will only match if the text is at the beginning of the string. This should solve :
if (preg_match("/(([A-Za-z0-9_]+=[A-Za-z0-9_]+)\|?)/m", "perPd_asd=as_3_4d|asdas=asdasd"))
return 'Valid';
return 'Invalid';
It is possible that parameter name starts from number?
You need more test cases for your regular expression, for example:
0=somevalue
param=value|
one_more_param=##$%^|some_param=some-value
_=VALUE|abc=***
a=1|b=2|c=3
param=0|param=1
my solution is:
^(([_A-Za-z][A-Za-z0-9_]*=[^\|=]+)\|)*([_A-Za-z][A-Za-z0-9_]*=[^\|=]+)$

php regexp: can't exclude one element

I am trying to set-up a quite complex regexp, but I can't avoid just one element from not-match list.
My regular expression is:
1234567-8_abc((?!_ABC|_DEFGHI)[\w]?)*(\.ios|\.and)
What I have to exclude is:
1234567-8_abc.ios
1234567-8_abc_DEFGHI.ios
1234567-8_abc_ABC.ios
Instead, what I have to include is:
1234567-8_abc_1UP.ios
1234567-8_abc_FI.ios
1234567-8_abc_gmg.ios
1234567-8_abc_1UP.and
1234567-8_abc_FI.and
1234567-8_abc_gmg.and
1234567-8_abc_ddd.and
1234567-8_abc_qwert.ios
1234567-8_abc_88.ios
Well, I can't exclude the first option (1234567-8_abc.ios).
I tried it here.
How can I achieve this?
Thank you!
You can use this pattern:
1234567-8_abc_[^_.]++(?<!_ABC|_DEFGHI)\.(?:ios|and)
Note: I assume that each substring between _ and .ios doesn't contain a dot or an underscore.
The possessive quantifier ++ is necessary to fail faster with the less possible backtracking steps
This regex matches your examples in PHP:
1234567-8_abc_((?!ABC|DEFGHI)[\w]?)*(\.ios|\.and)
Add a negative lookahead like below,
1234567-8_abc(?!_ABC|_DEFGHI)\w+(\.ios|\.and)
DEMO
(?!_ABC|_DEFGHI) Negative lookahead asserts that the string following _abc wouldn't be _ABC or _DEFGHI . And it must have one or more word characters before .ios or .and. So it won't match this 1234567-8_abc.ios string.
1234567-8_abc(?:(?!_ABC|_DEFGHI)\w)+(\.ios|\.and)
Try this.Your regex has left \w after 1234567-8_abc optional.Just made it compulsary.See demo.
http://regex101.com/r/bB8jY7/1

Regex for a string used for save a telephone number

I have a question. How should look a regex for the following words:
+23456745678 or +29845281058, (with comma)
I tried but no result:
if (!preg_match('#^\+[0-9]{11}$#',$string)) {
return ("Msisdn $string is incorrect!");
break;
}
Always I get this error.
Please help me. Thx in advance
The pattern should be:
'/\+[0-9]{11},?/'
The ^ in the beginning and $ at the end stand for beginning and end of line, which I am not sure if you really want there (my guess is not).
Test it here: http://www.phpliveregex.com/p/78v
Another option is to use \d for digit
'/\+\d{11},?/'

Use regular expressions to validate passwords

I have a password field which should match the following conditions
should have at least one letter and one digit
should have minimum length of 5 and maximum length of 20
Also, I would like to know if regular expressions are the same for all languages?
Links to good tutorials to get started with Regular Expressions (assuming I have just a basic understanding) would also be nice.
Thank you
The min and max just use strlen.
The one character and one digit I would use preg_match:
$len = strlen($string);
if ($len < 5) {
// too short
}elseif ( $len > 20) {
// too long.
}elseif (!preg_match('#[0-9]#', $string)) {
// does not contain a digit
}elseif (!preg_match('#[a-z]#i', $string)) {
// does not have a character
}
I like to break mine out to multiple checks so I can tell the user exactly what is missing. Some people prefer it bundled into one.
Regular expressions are a very good tool for password validation. Multiple rules can be applied using lookahead assertions (which work using AND logic) applied from the beginning of the string like so:
$re = '/
# Match password with 5-20 chars with letters and digits
^ # Anchor to start of string.
(?=.*?[A-Za-z]) # Assert there is at least one letter, AND
(?=.*?[0-9]) # Assert there is at least one digit, AND
(?=.{5,20}\z) # Assert the length is from 5 to 20 chars.
/x';
if (preg_match($re, $text)) {
// Good password
}
Here's the Javascript equivalent:
var re = /^(?=.*?[A-Za-z])(?=.*?[0-9])(?=.{5,20}$)/;
if (re.test(text)) {
// Good password
}
A good article regarding password validation using regex is: Password Strength Validation with Regular Expressions. (Although his final expressions include an erroneous dot-star at the beginning - see my comment on his blog).
Also note that regex syntax does vary from language to language (but most are converging on the Perl syntax). If you really want to know regex (in the Neo: "I know Kung-Fu" sense), then there is no better way than to sit down and read: Mastering Regular Expressions (3rd Edition) By Jeffrey Friedl.
Additional: A good argument can be made that password validation should be split up into multiple tests which allows the code to give specific error messages for each type of validation error. The answer provided here is meant to demonstrate one correct way to validate multiple rules using just one regular expression.
Happy regexing!

Regex to validate username

I'm trying to understand what's wrong with this regex pattern:
'/^[a-z0-9-_\.]*[a-z0-9]+[a-z0-9-_\.]*{4,20}$/i'
What I'm trying to do is to validate the username. Allowed chars are alphanumeric, dash, underscore, and dot. The restriction I'm trying to implement is to have at least one alphanumeric character so the user will not be allowed to have a nickname like this one: _-_.
The function I'm using right now is:
function validate($pattern, $string){
return (bool) preg_match($pattern, $string);
}
Thanks.
EDIT
As #mario said, yes,t here is a problem with *{4,20}.
What I tried to do now is to add ( ) but this isn't working as excepted:
'/^([a-z0-9-_\.]*[a-z0-9]+[a-z0-9-_\.]*){4,20}$/i'
Now it matches 'aa--aa' but it doesn't match 'aa--' and '--aa'.
Any other suggestions?
EDIT
Maybe someone wants to deny not nice looking usernames like "_..-a".
This regex will deny to have consecutive non alphanumeric chars:
/^(?=.{4,20}$)[a-z0-9]{0,1}([a-z0-9._-][a-z0-9]+)*[a-z0-9.-_]{0,1}$/i
In this case _-this-is-me-_ will not match, but _this-is-me_ will match.
Have a nice day and thanks to all :)
Don't try to cram it all into one regex. Make your life simpler and use a two step-approach:
return (bool)
preg_match('/^[a-z0-9_.-]{4,20}$/', $s) && preg_match('/\w/', $s);
The mistake in your regex probably was the mixup of * and {n,m}. You can have only one of those quantifiers, not *{4,20} both after another.
Very well, here is the cumbersome solution to what you want:
preg_match('/^(?=.{4})(?!.{21})[\w.-]*[a-z][\w-.]*$/i', $s)
The assertions assert the length, and the second part ensures that at least one letter is present.
Try this one instead:
'/[a-z0-9-_\.]*[a-z0-9]{1,20}[a-z0-9-_\.]*$/i'
Its probably just a matter if finetuning, you could try something like this:
if (preg_match('/^[a-zA-Z0-9]+[_.-]{0,1}[a-zA-Z0-9]+$/m', $subject)) {
# Successful match
} else {
# Match attempt failed
}
Matches:
a_b <- you might not want this.
ysername
Username
1254_2367
fg3123as
Non-Matches:
l__asfg
AHA_ar3f!
sAD_ASF_#"#T_
"#%"&#"E
__-.asd
username
1___
Non-matches you might want to be matches:
1_5_2
this_is_my_name
It is clear to me that you should split this into two checks!
Firstly check that they are using all valid characters. If they're not, then you can tell them that they are using invalid characters.
Then check that they have at least one alpha-numeric character. If they're not, then you can tell them that they must.
Two distinct advantages here: more meaningful feedback to the user and cleaner code to read and maintain.
Here is a simple, single regex solution (verbose):
$re = '/ # Match password having at least one alphanum.
^ # Anchor to start of string.
(?=.*?[A-Za-z0-9]) # At least one alphanum.
[\w\-.]{4,20} # Match from 4 to 20 valid chars.
\z # Anchor to end of string.
/x';
In Action (short form):
function validate($string){
$re = '/^(?=.*?[A-Za-z0-9])[\w\-.]{4,20}\z/';
return (bool) preg_match($re, $string);
}
Try this:
^[a-zA-Z][-\w.]{0,22}([a-zA-Z\d]|(?<![-.])_)$
From related question: Create one RegEx to validate a username
^[A-Za-z][A-Za-z0-9]*(?=.{3,31}$)[a-z0-9]{0,1}([a-z0-9._-][a-z0-9]+)*[a-z0-9.-_]{0,1}$
This will Validate the username
start with an alpha
accept underscore dash and dots
no spaces allowed
Why don't you make it simpler like this?
^[a-zA-Z][a-zA-Z0-9\._-]{3,9}
First letter should be Alphabetical.
then followed by character or symbols you allowed
length of the word should be between 4,10 (as explicitly force the first word)

Categories