Problems with preg_match function - php

I've just made a few edits to a file and when testing it seemed to not work, I did a bit of debugging and found that preg_match was returning 0, I've looked into it and cannot see what the problem is, also since I haven't touched this part of the file, I'm confused as to what might have happened...
<?php
echo preg_match('/[A-Z]+[a-z]+[0-9]+/', 'testeR123');
?>
This is a snippet I'm using for debugging, I'm guessing my pattern is wrong, but I am probably wrong about that.
Thanks,
P110

According to your comment:
I'm just looking for it to check if there is an uppercase, lowercase and a number, but from the replies, my pattern checks for it in an order
have a try with:
preg_match('/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[A-Za-z0-9]+$/', $input_string);
where
(?=.*[A-Z]) checks there are at least one uppercase
(?=.*[a-z]) checks there are at least one lowercase
(?=.*[0-9]) checks there are at least one digit
[A-Za-z0-9]+ checks there are only these characters.
(?=...) is called lookahead.

The problem is the order of the letters:
Try this:
echo preg_match('/[a-z]+[A-Z]+[0-9]+/', 'testeR123');
Or:
echo preg_match('/[A-Z]+[a-z]+[0-9]+/', 'Rtest123');
Or simpler
echo preg_match('/[A-Z]+[0-9]+/i', 'testeR123');

Your regex first test if there are Capital letters from A to Z then if there are lowercase letters from at to z and then if there are numbers. since your string starts with an lowercase it will not match.
i think you want to do this
[A-Za-z0-9]+
Or if you need that your string starts with a lowecase string then an uppercase string and then numbers you should change the regex to.
[a-z]+[A-Z]+[0-9]+
In that way your current string would fit the regex as well.

<?php
preg_match('/([A-Za-z0-9]+)/', 'testeR123', $match);
echo $match[1];
?>

Related

REGEX at last one uppercase and one number

I searched everywhere but i couldn't find the right regex for my verificaiton
I have a $string, i want to make sure it contains at last one uppercase letter and one number. no other characters allowed just numbers and letter. is for a password require.
John8 = good
joHn8 = good
jo8hN = good
I will use preg_match function
The uppercase and letter can be everywhere in the word, not only at the begging or end
This should work, but is a bit of a mess. Consider using multiple checks for readability and maintainability...
preg_match('/^[A-Za-z0-9]*([A-Z][A-Za-z0-9]*\d|\d[A-Za-z0-9]*[A-Z])[A-Za-z0-9]*$/', $password);
Use lookahead:
preg_match('/^(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]+$/', $string);
Use this regex pattrn
^([A-Z]+([a-z0-9]+))$
Preg_match
preg_match('~^([A-Z]+([a-z0-9]+))$~',$str);
Demo
Your requisition need "precise syntax description", and a lot of examples for assert your description. Only 3 or 4 examples is not enough, is very open.
For last confirmed update:
preg_match('/^([a-z]*\d+[a-z]*[A-Z][a-z]*|[a-z]*[A-Z][a-z]*\d+[a-z]*)$/',$str)
History
first solution preg_match('/^[A-Z][a-z]+\d+$/',$str)
After your edit1: preg_match('/^[a-z]*[A-Z][a-z]*\d+$/',$str)
After your comment about utf8: hum... add at your question the valid language. Example: "José11" is a valid string?
After your edit2 ("jo8hN" is valid): and about number, can repeat? Well I suppose not. "8N" is valid? I suppose yes. preg_match('/^([a-z]*\d+[a-z]*[A-Z][a-z]*|[a-z]*[A-Z][a-z]*\d+[a-z]*)$/',$str) you can add more possibilities with "|" in this regex.

regex to match string that only has one uppercase letter

I am curling an page and getting the output
however what is happening is that the html encoding is being removed so new lines are being skipped,
so it looks like this
This is Bob. He lives in an boatBut he only has one oar to row with.
in order to detect new lines I figure it was easier to just check for strings that only have One upper case letter and spaces inbetween, so far I have this
(\s\w+\s\w+.\s\D+[a-z][A-Z])
However this does not seem to work
as it only matches this
is Bob. He lives in an boatB
see here http://regex101.com/r/gH0lW1
how to match all strings that have spaces and match all strings up to one Uppercase letter
Update: this will split on the condition without losing any characters
<?php
$string = "This is Bob. He lives in an boatBut he only has one oar to row with.He also does stuff, it is cool.";
$array = preg_split('/(?<=[a-z.])(?=[A-Z])/', $string);
print_r($array);
?>
Use a positive lookbehind to ensure you capture a capital after a lowercase:
(?<=[a-z])[A-Z]
http://regex101.com/r/cB7bD8
You could use php's preg_split if you want, to explode the result on this regex.
(.*?(?:\w+(?=[A-Z]))|\1)
This regex has a recursive part that will match more than 1 sentence in a whole text. So you can check the Live demo and see the matched groups.
But,
If you wanna include a newline on each sentence begins after a period (.) as well, then I modify above regex to this:
(.*?(?:(?:\w+|\. *)(?=[A-Z]))|\1)
and now you can compare results with the first regex HERE

PHP, Regex - how to disallow non-alphanumeric characters

I'm trying to make a regex that would allow input including at least one digit and at least one letter (no matter if upper or lower case) AND NOTHING ELSE. Here's what I've come up with:
<?php
if (preg_match('/(?=.*[a-z]+)(?=.*[0-9]+)([^\W])/i',$code)) {
echo "=)";
} else {
echo "=(";
}
?>
While it gives false if I use only digits or only letters, it gives true if I add $ or # or any other non-alphanumeric sign. Now, I tried putting ^\W into class brackets with both a-z and 0-9, tried to use something like ?=.*[^\W] or ?>! but I just can't get it work. Typing in non-alphanums still results in true. Halp meeee
You need to use anchors so that it matches against the entire string.
^(?=.*[a-z]+)(?=.*[0-9]+)(\w+)$
Since you are using php, why even use regex at all. You can use ctype_alnum()
http://php.net/manual/en/function.ctype-alnum.php

Only allow a-z and space and the first letter of each word to be capitalized

Someone sitting on a regex that only allows a-z and ONLY allow the first letter of each word to be capitalized?
So 'Im detective John kimble" would be match but "Im a Cop yOu iDiot" would not be allowed
This regex will match a word with a lower-case or capital letter at the beginning of the word.
[a-zA-Z][a-z]*
Now you can extend the regex to match multiple such words depending on what exactly you want. You have to be a bit careful with this to make sure it handles strange cases like an empty sentence etc.
([a-zA-Z][a-z]*)* // Matches the empty sentence as well
([a-zA-Z][a-z]*)+ // Must have at least one word
Then you need to consider if the start and end characters (^ and $) are relevant for your pattern.
You really don't need regex for this that .. because i don't really think how is is an offence
You can simple correct the case :
$str = "joHn KiMBle";
echo ucwords(strtolower($str)); // John Kimble
In css you can capitalize the 1st letter of each word with:
.title {
text-transform: capitalize;
}
In PHP the string function ucfirst like this:
$foo = ucfirst($foo);
Allows only a-z use this regex in Javascript
var pat = /^[a-z]+$/;
Try using
([a-zA-Z][a-z]*)+
Hope it helps
You can use this pattern to check that:
^(?>[A-Za-z][a-z]*+|[^A-Za-z]++)+$
Doable without regex.
!(strspcn($text, "0123456789") !== false ||
ucwords($text) == ucwords(strtolower($text)))

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