2010-04-02 16 views
2

我的新手機無法識別電話號碼,除非其區號與來電相匹配。由於我住在愛達荷州,那裏的州內電話不需要區號,我的很多聯繫人都沒有區號保存。由於我的手機中儲存了數千個聯繫人,因此手動更新它們並不實際。我決定寫下面的PHP腳本來處理這個問題。它似乎工作得很好,除了我在隨機聯繫人的開頭找到重複的區號。使用正則表達式將PHP中的電話號碼修復爲PHP

<?php 
//the script can take a while to complete 
set_time_limit(200); 

function validate_area_code($number) { 
    //digits are taken one by one out of $number, and insert in to $numString 
    $numString = ""; 
    for ($i = 0; $i < strlen($number); $i++) { 
     $curr = substr($number,$i,1); 
     //only copy from $number to $numString when the character is numeric 
     if (is_numeric($curr)) { 
      $numString = $numString . $curr; 
     } 
    } 
    //add area code "208" to the beginning of any phone number of length 7 
    if (strlen($numString) == 7) { 
     return "208" . $numString; 
    //remove country code (none of the contacts are outside the U.S.) 
    } else if (strlen($numString) == 11) { 
     return preg_replace("/^1/","",$numString); 
    } else { 
     return $numString; 
    } 
} 
//matches any phone number in the csv 
$pattern = "/((1? ?\(?[2-9]\d\d\)? *)? ?\d\d\d-?\d\d\d\d)/"; 
$csv = file_get_contents("contacts2.CSV"); 
preg_match_all($pattern,$csv,$matches); 


foreach ($matches[0] as $key1 => $value) { 
    /*create a pattern that matches the specific phone number by adding slashes before possible special characters*/ 
    $pattern = preg_replace("/\(|\)|\-/","\\\\$0",$value); 

    //create the replacement phone number 
    $replacement = validate_area_code($value); 

    //add delimeters 
    $pattern = "/" . $pattern . "/"; 

    $csv = preg_replace($pattern,$replacement,$csv); 
} 
echo $csv; 

?> 

是否有更好的方法來修改CSV?另外,有沒有一種方法可以最大限度地減少通過CSV的次數?在上面的腳本中,preg_replace在非常大的String上被調用了數千次。

回答

0

多一點挖我自己揭示在我的問題正則表達式的問題。問題在於csv中的重複聯繫人。

實施例: (208)555-5555,555-5555

後第一遍變爲:

2085555555,208555555

和第二傳輸變得 2082085555555後,2082085555555

我工作圍繞這通過改變替換正則表達式:

//add escapes for special characters 
$pattern = preg_replace("/\(|\)|\-|\./","\\\\$0",$value); 
//add delimiters, and optional area code 
$pattern = "/(\(?[0-9]{3}\)?)? ?" . $pattern . "/"; 
0

啊程序...有時10分鐘的黑客更好。
如果是我......我會將CSV導入到Excel中,按照某種東西進行排序 - 可能是電話號碼的長度等等。爲固定電話號碼創建一個新列。當你有一組類似的犯規號碼時,請制定一個公式來解決。下一組相同。應該很快,不是?然後再次導出到.csv,省略壞道。

+0

感謝您的建議克里斯。我可以這樣做;但是我做了一個點使用的編程經常盡我所能來解決現實世界的問題。雖然我在解決問題的部分感興趣,我更感興趣的是與代碼這樣做,假設它可以幫助我學習。 – objectivesea 2010-04-02 01:33:40

+0

我完全理解 - 這將是一個很好的鍛鍊; Tibial。作爲PHP,如果你想出一個通用工具,你可以製作一個「修復我的電話簿」的網絡應用程序。這將是非常好的。 – 2010-04-02 01:43:57

2

如果我正確理解你,你只需要在該文件中任何位置的任何7位電話號碼前面加上區號,對吧?我不知道你在使用什麼樣的系統,但是如果你有一些體面的工具,這裏有幾個選項。當然,他們採取的方法大概可以在PHP中實現;這不僅是我的語言之一。

那麼,sed單線程怎麼樣?只需查找7位電話號碼,左邊的行首或逗號,右邊的逗號或行尾即可。

sed -r 's/(^|,)([0-9]{3}-[0-9]{4})(,|$)/\1208-\2\3/g' contacts.csv 

或者,如果你只想將它應用到某些領域,perl(或awk)會更容易。假設它的第二個字段:

perl -F, -ane '$"=","; $F[1]=~s/^[0-9]{3}-[0-9]{4}$/208-$&/; print "@F";' contacts.csv 

-F,指示字段分離器,$"是輸出字段分隔符(是的,它被分配一次每個環路,哦),陣列零索引,以便第二場是$F[1],有一個普通的替代品,並打印結果。

相關問題