簡體   English   中英

php正則表達式,從html文檔中提取電話號碼正則表達式

[英]php regex, extract like phone number regex from html documents

我正在嘗試從不同的html頁面提取特定信息。 基本上,該信息是10位數字,其格式可能不同,例如:

000-000-0000
000 - 000 - 0000
0000000000
please note that 000 - 000 - 0000000 is not a valid phone number so it should not extract the number if it contains any additional digits

我非常感謝您提供的幫助,以在所有3種情況下創建完美的正則表達式。 到目前為止,我只能使它僅適用於最后一個(最簡單的)。

這將與您列出的所有三個示例匹配。

(\d{3}\s*-?\s*\d{3}\s*-?\s*\d{4})

這是一個很好的起點:

<?php 

// all on one line... 
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';

// or broken up 
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})' 
        .'(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})' 
        .'[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/'; 

?> 

注意非捕獲子模式(看起來像(?:stuff) )。 這使格式化變得容易:

<?php 

$formatted = preg_replace($regex, '($1) $2-$3 ext. $4', $phoneNumber); 

// or, provided you use the $matches argument in preg_match 

$formatted = "($matches[1]) $matches[2]-$matches[3]"; 
if ($matches[4]) $formatted .= " $matches[4]"; 

?>

並為您提供了一些示例結果:

520-555-5542 :: MATCH 
520.555.5542 :: MATCH 
5205555542 :: MATCH 
520 555 5542 :: MATCH 
520) 555-5542 :: FAIL 
(520 555-5542 :: FAIL 
(520)555-5542 :: MATCH 
(520) 555-5542 :: MATCH 
(520) 555 5542 :: MATCH 
520-555.5542 :: MATCH 
520 555-0555 :: MATCH 
(520)5555542 :: MATCH 
520.555-4523 :: MATCH 
19991114444 :: FAIL 
19995554444 :: MATCH 
514 555 1231 :: MATCH 
1 555 555 5555 :: MATCH 
1.555.555.5555 :: MATCH 
1-555-555-5555 :: MATCH 
520-555-5542 ext.123 :: MATCH 
520.555.5542 EXT 123 :: MATCH 
5205555542 Ext. 7712 :: MATCH 
520 555 5542 ext 5 :: MATCH 
520) 555-5542 :: FAIL 
(520 555-5542 :: FAIL 
(520)555-5542 ext .4 :: FAIL 
(512) 555-1234 ext. 123 :: MATCH 
1(555)555-5555 :: MATCH

如果您允許像建議的那樣使用空格和破折號,您可能會得到很多誤報。

<?php
preg_match_all("/\+?[0-9][\d-\()-\s+]{5,12}[1-9]/", $string, $matches);
print_r($matches);
?>

\\b[0-9]{3}\\s*[-]?\\s*[0-9]{3}\\s*[-]?\\s*[0-9]{4}\\b

編輯

添加了單詞邊界。

除連字符外,還要考慮其他定界符,更不用說括號了。

(?:1\s*?[-.]?\s*)?(?:\(\s*d{3}\s*\)|d{3})\s*?[-.]?\s*\d{3}\s*?[-.]?\s*\d{4}\b

好的,也許這比您需要的要全面,但是實際上這可能會變得您想要的復雜。 您可以擴展它以查找國際電話號碼,分機號等,但這對您而言並不值得。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM