strtr() 用於轉換字串中特定字元,支援兩種呼叫方式:
strtr(string, from, to)
strtr(string, array)
| 參數 | 必要性 | 說明 |
|---|---|---|
| string | 必要 | 要轉換的字串 |
| from | 必要(除非用陣列) | 要被替換的字元 |
| to | 必要(除非用陣列) | 替換成的字元 |
| array | 必要(除非用 from/to) | 鍵值對應的替換對照表 |
注意:若 from 與 to 長度不同,會以較短者為準。
<?php
echo strtr("Hilla Warld", "ia", "eo");
?>
輸出: Hello World
說明:將 'i'→'e'、'a'→'o' 逐字元對應替換。
<?php
$arr = array("Hello" => "Hi", "world" => "earth");
echo strtr("Hello world", $arr);
?>
輸出: Hi earth
說明:以陣列鍵值對進行子字串替換,適合單詞級別替換。
str_replace(),strtr() 不會重複掃描已替換區域strtr() 通常快於 str_replace()