0

i am using the following code to detect if a string is a phone number...

<?php
$text = "example467676@gmail.com" ;
if (preg_match_all('/\+?[0-9][0-9()-\s+]{4,20}[0-9]/',$text)){
    echo "phone number";    
}else{
    echo "not a phone number";
}
?>

the problem is that i get phone number where as i should be getting not a phone number... how can i solve this problem... any help would be appreciated.

elixenide
  • 44,308
  • 16
  • 74
  • 100
asdf
  • 460
  • 1
  • 10
  • 31

3 Answers3

2

The problem is that {4,20} will match any string in which the preceding block appears 4 to 20 times, so it matches the digits in the sample email address. Try this:

<?php
$text = "example467676@gmail.com" ;
if (preg_match_all('/^\+?([0-9-]|\s|\([0-9]+\)){4,20}[0-9]/',$text)){
    echo "phone number";    
}else{
    echo "not a phone number";
}
?>

Regular expression visualization

Debuggex Demo

Note that preg_match_all requires 3 parameters in PHP < 5.4.

elixenide
  • 44,308
  • 16
  • 74
  • 100
  • your code works fine but the problem is i get not a phone number when i put in this +8801689347804 – asdf Dec 13 '13 at 18:59
  • 1
    That's because I didn't know you wanted to match `+` signs. I've updated it to match an optional `+` at the beginning. – elixenide Dec 13 '13 at 19:03
1

preg_match_all() starts from the first match until the last one.

In this case the first match would be 4, and it continues till 6. Ignoring all the other characters.

To make it start from the beginning use ^ (beginning of line anchor) before the regular expression. And to force it to continue until the end put $ (end of line anchor) at the end of the regular expression.

Like this:

<?php
$text = "example467676@gmail.com" ;
if (preg_match_all('/^+?[0-9][0-9()-\s+]{4,20}[0-9]/$', $text)) {
  echo "phone number";  
} else{
  echo "not a phone number";
}
?>
hwnd
  • 69,796
  • 4
  • 95
  • 132
0

If I understand your problem correctly, the regular expression you've got in your example is returning a match even when someone puts in an email address with numbers, like you have there.

Match to the beginning and end of the line only to avoid this, using ^ and $:

<?php
$text = "example467676@gmail.com" ;
if (preg_match_all('^/\+?[0-9][0-9()-\s+]{4,20}[0-9]$/',$text)){
    echo "phone number";    
}else{
    echo "not a phone number";
}
?>

Working example: http://regex101.com/r/xY0yU3

brandonscript
  • 68,675
  • 32
  • 163
  • 220