Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch repeat letters in PHP - Regular expressions

I have to check user input to make sure name, last name (etc...) are entered correctly and are valid. I have to build a regexp that check if a user enters repeated letters in the first name , last name etc...

Example:

  • AAAron = bad because of the 3 A's
  • AAron = good
  • Hannah = Good
  • Hannnah = bad because of the 3 N's

Is there a PHP regular expression to catch these cases? (I have a basic regexp knowledge but this is too much for me)

EDIT: This should Allow numbers as well: David 3 or III

Thanks

like image 750
Tech4Wilco Avatar asked Oct 25 '11 12:10

Tech4Wilco


2 Answers

You can use back reference for that purpose.

preg_match('/(\w)(\1+)/', $subject, $matches);
print_r($matches);

the \1 means repeat the first capture so in that case \w.

In the case of your example, I don't think using regular expression would be the best solution, why don't you just count the number of instance of any characters?

i.e.

$charCountArray = array();
foreach ($name as $char) {
    $charCountArray[$char]++;
}

back reference is an advanced feature, luckily the PCRE functions supports it.

Note: preg_match would match only one sequence, if you need to know all the matches please use preg_match_all

like image 159
RageZ Avatar answered Oct 04 '22 21:10

RageZ


Try this regular expression:

/(\w)\1{2}/
like image 22
Aziz Shaikh Avatar answered Oct 04 '22 20:10

Aziz Shaikh