-4

I want to check if users are putting their phone number into a string.

Just need to check for 6 numbers (digits) in a row.

What is the best way to do this in PHP?

Example String:

blah blah553376and blah

Avatar
  • 14,622
  • 9
  • 119
  • 198
Adam
  • 19,932
  • 36
  • 124
  • 207
  • This question appears to be off-topic because "how do I do this arbitrary thing" is not a real question. – Marty Aug 06 '14 at 06:53
  • Legit question IMO. Helpful is also https://stackoverflow.com/q/11023753/1066234 – Avatar Apr 18 '20 at 16:51

2 Answers2

2

Try this

$str = "blah blah553376and blah";
preg_match('!\d+!', $str, $matches);//You can use preg_match('!\d{6,}!', $str, $matches); also
if(isset($matches[0]) && is_numeric($matches[0]) && strlen(trim($matches[0])) >= 6){
  echo $matches[0];
}
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
0

There are a few ways to approach this problem:

  1. The regex solution, as pointed out by some others. I'm in no way a regex expert, but this seems to work:

    $input_line="blah blah553376and blah";
    $regex_line="/([a-z 0-9]*)([0-9]{6})([a-z 0-9]*)/i";
    $output_array=Array();
    preg_match($regex_line, $input_line, $output_array);
    if($output_array[2])
    {
        echo("number is:  ". $output_array[2]);
    }
    else
    {
        echo("number not found");
    }
    
  2. The exhaustive iteration method:

    $input_line="blah blah553376and blah";
    
    $output_string="";
    for($i=0; $i<strlen($input_line);$i++)
    {
        $current_character = substr($input_line,$i,1);
        if(is_numeric ( $current_character ))
        {
            $output_string .= $current_character;
        }
        else
        {
            //reset output
            $output_string="";
        }
    
        if(strlen($output_string) >=6)
        {
            //bail out if requirements are met.
            break;
        }
    }
    if($output_string)
    {
        echo("number is:  " . $output_string);
    }
    else
    {
        echo("number not found");
    }
    
  3. I'm sure there are other better ways, but above are just two simple ways off the top of my head to approach this.

nanytech
  • 398
  • 3
  • 10