2017-05-08 173 views
1

我想寫一個小腳本來找出給定的字符串是否包含電話號碼和/或電子郵件地址。PHP - 搜索字符串的電話號碼和電子郵件

這裏是我到目前爲止有:

function findContactInfo($str) { 
    // Find possible email 
    $pattern = '/[a-z0-9_\-\+][email protected][a-z0-9\-]+\.[a-z]{2,3}?/i'; 
    $emailresult = preg_match($pattern, $privateMessageText); 

    // Find possible phone number 
    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]; 
} 

的部分與郵件工作正常,但我願意接受改進。 隨着電話號碼我有一些問題。首先,將被賦予該函數的字符串很可能包含德語電話號碼。這個問題是所有不同的格式。它可能類似於 030 - 1234567或030/1234567或02964-723689或01718290918 等。所以基本上我幾乎不可能找出什麼樣的組合會被使用。所以我在想的是,也許最好是找到至少三位數字的組合。例如:

$stringOne = "My name is John and my phone number is 040-3627781"; 
// would be found 

$stringTwo "My name is Becky and my phone number is 0 4 0 3 2 0 5 4 3"; 
// would not be found 

我遇到的問題是我不知道如何找到這樣的組合。即使經過近一個小時的網絡搜索,我找不到解決方案。 有沒有人有如何解決這個問題的建議? 謝謝!

+0

怎麼樣:'/ \ b [\ d - \ /] {4,} \ b /'?演示在這裏: https://regex101.com/r/lbemPI/1 – degant

+0

它給了我這個錯誤: 警告:preg_match()期望參數2是字符串,在 – Dennis

+0

給出的數組中給出的數字格式爲「 3-3-4'作爲一種官方或商業形式,但人們往往會分享他們的號碼,而非法國人,比如'3-2-2-2-2-2'。來源:*德國朋友。* – Martin

回答

2

你可以使用

\b\d[- /\d]*\d\b 

a demo on regex101.com


龍版本:

\b\d  # this requires a "word boundary" and a digit 
[- /\d]* # one of the characters in the class 
\d\b  # a digit and another boundary. 


PHP

<?php 
$regex = '~\b\d[- /\d]*\d\b~'; 

preg_match_all($regex, $your_string_here, $numbers); 
print_r($numbers); 
?> 

問題與此是,你可能會得到大量的誤報,所以它肯定會提高你的準確度時,這些比賽清理,標準化,然後針對數據庫進行測試。


至於你 的問題通過電子郵件,我經常使用:

\[email protected]\S+ 
# not a whitespace, at least once 
# @ 
# same as above 

有幾十個不同的有效電子郵件,以證明的唯一辦法,如果有一個實際的人後面一個是從一個發送電子郵件鏈接(即使這可能是自動的)。

+0

完美!非常感謝。 – Dennis

+0

@丹尼斯:不客氣,很樂意幫忙。 – Jan

相關問題