2013-01-04 149 views
0

我有一個網站需要向用戶顯示電話號碼,但不是顯示某人從源代碼中收穫的實際數字,而是想要替換電話的每個數字數字與相應的單詞。例如...PHP str_replace用單詞替換數字

355-758-0384 

Would become 

three five five - seven five eight - zero three eight four 

可以這樣做嗎?對不起,我沒有任何代碼顯示,因爲我甚至不知道從哪裏開始。

回答

6
$string="355-758-0384"; 
$search = array(0,1,2,3,4,5,6,7,8,9); 
$replace = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'); 
echo str_replace($search, $replace, $string); 

然後你可以藏漢使用任何不同的字符串,而不必更新代碼

編輯:

如果你想自動空間上的末尾,則您的$替換陣列可以

$replace = array('zero ', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine '); 
+0

謝謝我最終編輯了一些空格,併爲短劃線添加了一些間距。這非常簡潔和有效。 – Budove

+0

非常歡迎! –

1
str_replace(' ', ' ', strtr($phone_number, array(
    '0' => ' zero ', 
    '1' => ' one ', 
    ... 
)))