Domanda

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

È stato utile?

Soluzione

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.

Altri suggerimenti

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];
?>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top