-3

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Soumya
  • 425
  • 1
  • 6
  • 28

2 Answers2

0

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

Steve P.
  • 14,489
  • 8
  • 42
  • 72
0
 $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);
Code Lღver
  • 15,573
  • 16
  • 56
  • 75