2013-08-06 113 views
-3

我想從整個句子中搜索電話號碼。它可以是任何具有像(122)221-2172或122-221-2172或(122)-221-2172這樣的模式的數字,在PHP的幫助下我不知道數字存在於句子的哪一部分或我可以使用substr。搜索號碼模式

+2

學習正則表達式,隊友。 – sashkello

+0

你可以顯示電話號碼的模式嗎? –

+0

這就是問題,因爲電話號碼可以是123-123-1234或(123)123-1234或(123)-123-1234或123 123 1234.任何 – Soumya

回答

0

您可以使用regular expressions來解決這個問題。不是100%的PHP語法,但我想這將是這個樣子:

$pattern = '/^\(?\d{3}\)?-\d{3}-\d{4}/'; 

^說 「開始」
\(逃脫(
\(?說0或1 (
\d{x}說正是x

您可能還想檢出Using Regular Expressions with PHP

0
$text = 'foofoo 122-221-2172 barbar 122 2212172 foofoo '; 
$text .= ' 122 221 2172 barbar 1222212172 foofoo 122-221-2172'; 

$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);