Search a Number pattern

825 Views Asked by At

I want to search a phone number from a whole sentence. It can be any number with a pattern like (122) 221-2172 or 122-221-2172 or (122)-221-2172 by help of PHP where I don't know in which part of the sentence that number is exists or I could use substr.

2

There are 2 best solutions below

0
On

You can use regular expressions to solve this. Not 100% on php syntax, but I imagine it would look something like:

$pattern = '/^\(?\d{3}\)?-\d{3}-\d{4}/';

^ says "begins with"
\( escapes the (
\(? say 0 or 1 (
\d{x} says exactly x numbers

You may also want to check out Using Regular Expressions with PHP

0
On
 $text = 'foofoo 122-221-2172 barbar 122 2212172 foofoo ';
$text .= ' 122 221 2172 barbar 1222212172 foofoo 122-221-2172';

$matches = array();

// returns all results in array $matches
preg_match_all('/[0-9]{3}[\-][0-9]{6}|[0-9]{3}[\s][0-9]{6}|[0-9]{3}[\s][0-9]{3}[\s][0-9]{4}|[0-9]{9}|[0-9]{3}[\-][0-9]{3}[\-][0-9]{4}/', $text, $matches);
$matches = $matches[0];

var_dump($matches);