I have the following code for validating user input for alpha numeric characters
if (!preg_match("/^[A-Za-z][A-Za-z0-9.]*(?:_[A-Za-z0-9]+)*$/", $username)){
echo "invalid username";
}
It checks, whether the input have other characters than (A-Z) (0-9) alpha numeric. Additionally it allows to accept (_) underscore also, but it should be placed in between the strings only as my_name, but it will not accept _myname or myname_.
My question is how can I add a dot(.) character in my above code as same as constrained in underscore as Eg accept (my.name) or (myn.ame) etc but not to accept (.myname) (myname.)
I think this pattern should work for you
$string = 'my_nam.e';
$pattern = '/^[a-z]+([a-z0-9._]*)?[a-z0-9]+$/i';
if ( ! preg_match($pattern, $string))
{
echo 'invalid';
}
Related
I'm using preg_match and its working to allow; numbers, letters and dash. but i want to limit the dash to 1 only. i tried added {1} before and after the dash but its still allowing more than one. what am i doing wrong?
if (!preg_match("/^[A-Za-z0-9-]+$/", $username)) {
$nameErr = "The username you selected was invalid.<br>Valid characters are dashes (one only), letters and numbers.";
} else {
This is the code that i'm using.
Thanks
Make an extra test for the dash count to keep it simple.
if (!preg_match("/^[A-Za-z0-9\-]+$/", $username) || substr_count($username,'-') > 1) {
$nameErr = "The username you selected was invalid.<br>Valid characters are dashes (one only), letters and numbers.";
}
Since you seem to validate a string that can contain one or zero hyphens in an alphanumeric string, you may use a negative lookahead in your pattern to fail the match if 2 hyphens are found:
"/^(?![^-]*-[^-]*-)[A-Za-z0-9-]+$/D"
^^^^^^^^^^^^^^^^
Pattern details:
^ - start of a string
(?![^-]*-[^-]*-) - fail the match if there are 2 hyphens separated with 0+
chars other than -
[A-Za-z0-9-]+ - 1 or more alphanumeric chars or hyphens
$ - the very end of the string (since /D modifier is used).
See a regex demo (pattern modified to account for a multiline string input).
Note that if you want to disallow - to appear at the start/end of the string, and several consecutive -s, use a more straight-forward pattern:
"/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)?$/D"
where ^[A-Za-z0-9]+ will match 1+ alphanumeric chars at the start of the stirng, and (?:-[A-Za-z0-9]+)?$ will match 1 or 0 occurrences of a - followed with 1+ alphanumeric chars at the end of the string.
$username = "abc-edf-tru-ksk-5-ll-hr-foam-6-inch-queen-anroid-phone-stackoverflow-72-x-70-x-6290321_1";
This below code allow hypens(-) and underscore(_)
if(preg_match('/^[a-zA-Z0-9\-\_]+(-[a-zA-Z0-9\-\_]+)*$/', $username))
{
echo "The username you selected valid characters are hypens,underscores, letters and numbers.";
}
allow only hypen(-)
if(preg_match('/^[a-zA-Z0-9\-]+(-[a-zA-Z0-9\-]+)*$/'), $username))
{
echo "The username you selected valid characters are hypens(only), letters and numbers.";
}
allow only underscore(_)
if(preg_match('/^[a-zA-Z0-9\_]+(-[a-zA-Z0-9\_]+)*$/'), $username))
{
echo "The username you selected valid characters are underscores(only),underscores, letters and numbers.";
}
not allow hypens, underscores and symbols
if(preg_match('/^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$/'), $username))
{
echo "The username you selected valid characters are letters and numbers.";
}
i need to validate a string that can only have letters(lowercase or uppercase) and may have space (may not have too) and a dash.
if(preg_match('/^[-a-zA-Z0-9]+$/', $myString)) {
//valid string
}
You could use this for a string contains only letter, space and dash, but at least one letter.
if(preg_match('/^(?=.*[a-z])[a-z -]+$/i', $myString)) {
echo 'valid';
}
Edit:
If the input must begin with any letter, then the regex could be simplified to:
if(preg_match('/^[a-z][a-z -]*$/i', $myString)) {
echo 'valid';
}
You can use this regex:
/^[a-zA-Z -]+$/
if(preg_match('/^[a-zA-Z -]+$/', $myString)) {
//valid string
}
EDIT If input must start with a letter then use:
/^[a-zA-Z][a-zA-Z -]*$/
I'm trying to write a regular expression which could match a string that possibly includes Chinese characters. Examples:
hahdj5454_fd.fgg"
example.com/list.php?keyword=关键字
example.com/list.php?keyword=php
I am using this expression:
$matchStr = '/^[a-z 0-9~%.:_\-\/[^x7f-xff]+$/i';
$str = "http://example.com/list.php?keyword=关键字";
if ( ! preg_match($matchStr, $str)){
exit('WRONG');
}else{
echo "RIGHT";
}
It matches plain English strings like that dasdsdsfds or http://example.com/list.php, but it doesn't match strings containing Chinese characters. How can I resolve this?
Assuming you want to extend the set of letters that this regex matches from ASCII to all Unicode letters, then you can use
$matchStr = '#^[\pL 0-9~%.:_/-]+$#u';
I've removed the [^x7f-xff part which didn't make any sense (in your regex, it would have matched an opening bracket, a caret, and some ASCII characters that were already covered by the a-z and 0-9 parts of that character class).
This works:
$str = "http://mysite/list.php?keyword=关键字";
if (preg_match('/[\p{Han}]/simu', $str)) {
echo "Contains Chinese Characters";
}else{
exit('WRONG'); // Doesn't contains Chinese Characters
}
I'm validating my contact form using PHP and I've used the following code:
if (ctype_alpha($name) === false) {
$errors[] = 'Name must only contain letters!';
}
This code is works fine, but it over validates and doesn't allow spaces. I've tried ctype_alpha_s and that comes up with a fatal error.
Any help would be greatly appreciated
Regex is overkill and will perform worse for such a simple task, consider using native string functions:
if (ctype_alpha(str_replace(' ', '', $name)) === false) {
$errors[] = 'Name must contain letters and spaces only';
}
This will strip spaces prior to running the alpha check. If tabs and new lines are an issue you could consider using this instead:
str_replace(array("\n", "\t", ' '), '', $name);
ctype_alpha only checks for the letters [A-Za-z]
If you want to use it for your purpose, first u will have to remove the spaces from your string and then apply ctype_alpha.
But I would go for preg_match to check for validation. You can do something like this.
if ( !preg_match ("/^[a-zA-Z\s]+$/",$name)) {
$errors[] = "Name must only contain letters!";
}
One for the UTF-8 world that will match spaces and letters from any language.
if (!preg_match('/^[\p{L} ]+$/u', $name)){
$errors[] = 'Name must contain letters and spaces only!';
}
Explanation:
[] => character class definition
p{L} => matches any kind of letter character from any language
Space after the p{L} => matches spaces
+ => Quantifier — matches between one to unlimited times (greedy)
/u => Unicode modifier. Pattern strings are treated as UTF-16. Also
causes escape sequences to match unicode characters
This will also match names like Björk Guðmundsdóttir as noted in a comment by Anthony Hatzopoulos above.
if (ctype_alpha(str_replace(' ', '', $name)) === false) {
$errors[] = 'Name must contain letters and spaces only';
}
How can I alter the pattern below to allow 1 space character ?
$name = 'too long name';
$pattern_name = '/[^a-zA-Z]/';
if (preg_match($pattern_name,$name)) { // remove any non-letter characters
$name = preg_replace($pattern_name,'',$name);
$errors['name'] = 'Invalid characters found and removed in name';
}
Using either of these patterns does not work:
$pattern_name = '/[^a-zA-Z ?]/';
$pattern_name = '/[^a-zA-Z] ?/';
Expected result is a match, since 2 space characters exists in $name, thus the if-statement should be true and the replace function will update $name so its value will become "too longname".
You'll have to make your pattern more explicit. If you can have one space at maximum, and it must be surrounded by letters, then:
$pattern_name = '/^[a-z]+( [a-z]+)?$/i';
It should be as simple as adding a space in the brackets.
$pattern_name = '/[^a-zA-Z ]/';
I'd invert the regex, and instead of trying to find invalid characters, match valid names (is that what you are doing?). That gives us this regex: /[a-zA-Z]+ [a-zA-Z]+/. Match valid characters, one space and then more valid characters.