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.
Asked
Active
Viewed 807 times
-3
-
2Learn regular expressions, mate. – sashkello Aug 06 '13 at 05:35
-
Can you show the pattern of phone number.? – 웃웃웃웃웃 Aug 06 '13 at 05:35
-
Thats the problem because the phone number can be 123-123-1234 or (123) 123-1234 or (123)-123-1234 or 123 123 1234. anything – Soumya Aug 06 '13 at 05:36
-
@sashkello. With my knowledge I couldn't do it or else I wouldn't ask this question here. – Soumya Aug 06 '13 at 05:43
-
@Soumya I believe that my response is a solution to your problem, but I don't know php... – Steve P. Aug 06 '13 at 05:45
-
@Soumya Then post your previous attempts. – Daedalus Aug 06 '13 at 05:46
2 Answers
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

ritwikVerma
- 1
- 1