asdf
asdf

Reputation: 460

Identify phone number in a string

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

<?php
$text = "[email protected]" ;
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.

Upvotes: 0

Views: 413

Answers (3)

user2203117
user2203117

Reputation:

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 = "[email protected]" ;
if (preg_match_all('/^+?[0-9][0-9()-\s+]{4,20}[0-9]/$', $text)) {
  echo "phone number";  
} else{
  echo "not a phone number";
}
?>

Upvotes: 1

elixenide
elixenide

Reputation: 44851

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 = "[email protected]" ;
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.

Upvotes: 2

brandonscript
brandonscript

Reputation: 73034

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 = "[email protected]" ;
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

Upvotes: 0

Related Questions