Find phone numbers in a string
In PHP I'm searching for phonenumbers in a certain text.
I use explode()
to divide the text in different parts,using the area code of the city I'm searching for as the delimiter. The problem is that phonenumbers that include the same numbers as the area-code are not returned well.
For example:
"foofoo 010-1234567 barbar"
splits into "foofoo "
and "-1234567 barbar"
but
"foofoo 010-1230107 barbar"
splits into "foofoo "
, "-123"
and "7 barbar"
!
I can use the first one to reconstruct the phonenummer with the areacode, but the second goes wrong of course...
I guess I need a regular expression to split the text with some kind of mechanism to not split on short strings, instead of explode()
, but I don't know how to do it.
Any ideas or a better way to search for phonenumbers in a text ?
UPDATE: The format is NOT consistent, so looking for the hyphen is no solution. Some phone numbers have spaces between th开发者_如何学JAVAe area code and number, some have hooks, some have nothing, etc. Dutch phonenumbers have an areacode of 2,3 or 4 numbers and are usually 10 numbers in total.
To find phone numbers like:
- 010-1234010
- 010 1234010
- 010 123 4010
- 0101234010
- 010-010-0100
Try this:
$text = 'foofoo 010-1234010 barbar 010 1234010 foofoo ';
$text .= ' 010 123 4010 barbar 0101234010 foofoo 010-010-0100';
$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);
You could use a regular expression to match the phone numbers. There are many, many ways to skin this particular cat (and likely many identical questions here on SO) a super-basic example might look like the following.
$subject = "foofoo 010-1230107 barbar 010-1234567";
preg_match_all('/\b010-\d+/', $subject, $matches);
$numbers = $matches[0];
print_r($numbers);
The above would output the contents of the $numbers
array.
Array
(
[0] => 010-1230107
[1] => 010-1234567
)
If you delete all of the non numeric characters, you will only be left with the phone number. You can then take that string and parse it into ###-###-####
if you wish.
$phone = preg_replace('/\D/', '', 'Some test with 123-456-7890 that phone number');
//$phone is now 1234567890
echo substr($phone, 0, 3);//123
echo subsr($phone, 3, 3);//456
echo substr($phone, 6);//7890
Not sure if that is what you are looking for or not.
精彩评论