Capture all phones from a text file

Asked

Viewed 151 times

1

I have a log records in html, and would like to capture all the phone numbers, both fixed and mobile that are scattered throughout the file, I use the following regular expression currently: /(\(?\d{2}\)?) ?9?\d{4}-?\d{4}/, only she’s missing some numbers that aren’t phones, which is wrong?

preg_match_all('/(\(?\d{2}\)?) ?9?\d{4}-?\d{4}/', $phone, $out);

echo '<pre/>';
print_r(array_shift($out));

number you passed: 99988877766

  • You can [Edit] the question and add examples of which numbers are being captured but which are not phones?

  • show an excerpt from that file. Without it is unviable

  • for example, dashless Cpfs are passing.

  • 1

    Put an example of your file, cite all the formats that exist in the phone number file. I did not understand your comment about CPF, and this wanting to capture Phone Number.

1 answer

1

Depends on the pattern of numbers

An example of regular expression:

/(?:\((\d{2})\))?\s?(\d{3,5}[-\s]?\d{4})/

It will capture, in group 1 the DDD and in group 2 the number, including strokes or spaces.

Patterns she captures:

(11)1234-0000
11-123-4567
11-1234567
(11)1234-1234
(11)123-1203
(11)12349-0293
1234-2039
99888-9292

To get more correct in the capture you must first search all the possibilities of formats that you have in your file. For example, this expression does not capture numbers that have the international dial code.

To test the expressions you can use the PHP Live Regex. It allows you to do the tests online.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.