2

I've got a Call Me Back form which sends me a phone number of a person who wants to be called back. Today I received the form with '88888888' instead of a real phone number.

How can I check if the string contains 1 and the same number, continous? There must not be more than 4 same numbers in a row.

Kara
  • 6,115
  • 16
  • 50
  • 57
Chloë Vd Eeden
  • 41
  • 1
  • 1
  • 7
  • 9
    This is going to piss off anyone who, for whatever reason, has a legit number with 4 consecutive identical digits. And it's going to do nothing for whoever sent you 88888888; next time they 'll send 12345678. – Jon Mar 21 '13 at 22:38
  • Assuming you want to validate a North American telephone number: [see this answer](http://stackoverflow.com/questions/3357675/validating-us-phone-number-with-php-regex). – couzzi Mar 21 '13 at 22:38
  • 4
    Don't try and validate telephone numbers just like you should never try and validate names. That said, `/^(\d)\1+$/` – DaveRandom Mar 21 '13 at 22:40
  • 1
    @couzzi Actually I am trying to check a Dutch phone number :). It's not that I want to fully validate it, just check if it has just got 1 number in it, which continous (8888888888 or 5555555555, 444444444 etc) – Chloë Vd Eeden Mar 21 '13 at 22:46
  • Please reconsider this question's duplicate status: [The answer noted above](http://stackoverflow.com/questions/3792908/php-regular-expression-repeated-characters) has solutions that match *consecutive* characters, regardless of the beginning or end of the string. OP seeks a solution which determines if a string contains *one exclusive* character *repeatedly*. For example, [The suggested answer](http://stackoverflow.com/questions/3792908/php-regular-expression-repeated-characters) would fail for `88888889`, amongst many others. – couzzi Mar 22 '13 at 03:33

2 Answers2

3

To check if the string contains only one repeated integer, string -> array, check if the unique count is 1.

<?php

$string  = "88888888"; 

$array = array_unique( str_split( $string ) );

$result = $array;

if( count($result) === 1 ) {
    echo "Same number repeated in string";
}else{
    echo "More than 1 number found in string";
}

?>

-Edit-

optimized: Removed for loop thanks to comment by @Uberfuzzy

couzzi
  • 6,316
  • 3
  • 24
  • 40
  • 2
    You can kill your `for` loop by using [str_split](http://www.php.net/manual/en/function.str-split.php). `$array = array_unique( str_split( $string ) );` – Uberfuzzy Mar 21 '13 at 23:23
  • 1
    This worked great for me thanks! You can also kill the $length variable (I'm assuming it was used in the for loop that was removed). – Kelly Cook May 29 '14 at 02:10
1
$number_string = (string)$number_string;
return strlen($number_string) > 0 && str_repeat($number_string[0], strlen($number_string)) === $number_string;
sectus
  • 15,605
  • 5
  • 55
  • 97