string strtr(string $str, string $from, string $to)
將 `$from` 中的每個字元對應替換為 `$to` 同位置的字元。長度以較短者為準。
<?php
echo strtr('hilla warld', 'ia', 'eo'); // hello world
// 逐字元對應:
// i -> e
// a -> o
// 多餘的 'a' 被忽略
string strtr(string $str, array $replace_pairs)
鍵為搜尋字串,值為替換字串。**支援多字元搜尋、最長優先匹配、不重複替換已替換部分**。
$trans = array(
'hello' => 'hi',
'hi' => 'hello',
'world' => 'earth'
);
echo strtr('hi all, i said hello world', $trans);
// hello all, i said hi earth
// 執行順序:最長鍵優先
// 'hello' (5字) 先於 'hi' (2字) 匹配
// 替換後不再掃描已替換區域
| 特性 | strtr($str, $arr) | str_replace($search, $replace, $str) |
|---|---|---|
| 搜尋單位 | 字串(多字元) | 字串(多字元) |
| 匹配策略 | 最長優先、不重疊 | 依陣列順序、可重疊替換 |
| 已替換區域 | 不再掃描 | 會再次掃描(可能連鎖替換) |
| 大小寫敏感 | 是 | 是 |
| 效能(大量替換) | 通常較快 | 較慢 |
$str = 'a'; $replace = ['a'=>'b', 'b'=>'c']; // str_replace:按順序執行,a->b,再 b->c,結果 'c' echo str_replace(array_keys($replace), array_values($replace), $str); // c // strtr:最長優先(同長度按陣列順序),a->b 後停止,結果 'b' echo strtr($str, $replace); // b
function render_template($template, $data) {
$replace = array();
foreach ($data as $key => $value) {
$replace['{{' . $key . '}}'] = $value;
}
return strtr($template, $replace);
}
$tpl = 'Hello {{name}}, welcome to {{site}}!';
$data = ['name' => 'John', 'site' => 'Example.com'];
echo render_template($tpl, $data);
// Hello John, welcome to Example.com!
$html_entities = array(
'&' => '&',
'<' => '<',
'>' => '>',
'"' => '"',
"'" => ''',
);
function html_encode($str) {
global $html_entities;
return strtr($str, $html_entities);
}
function html_decode($str) {
global $html_entities;
return strtr($str, array_flip($html_entities));
}
$normalize_map = array(
' ' => ' ', // 全形空格
'!' => '!',
'?' => '?',
':' => ':',
';' => ';',
'(' => '(',
')' => ')',
// ... 更多對應
"\x00" => '', "\x01" => '', "\x02" => '', // 移除控制字元
);
$clean = strtr($input, $normalize_map);
<?php
$str = str_repeat('abcdefghijklmnopqrstuvwxyz', 10000);
$map = array_combine(range('a','z'), range('A','Z'));
$start = microtime(true);
strtr($str, $map);
echo "strtr: " . (microtime(true) - $start) . "s\n";
$start = microtime(true);
str_replace(array_keys($map), array_values($map), $str);
echo "str_replace: " . (microtime(true) - $start) . "s\n";
// 典型結果:strtr 約 2-3 倍快於 str_replace