萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP strtr() 函數完整指南:字元轉換與字串替換雙模式詳解

strtr() 兩種呼叫模式

模式一:三參數字元對字元轉換

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() vs str_replace() 關鍵差異

特性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

進階應用範例

1. 模板引擎簡易實作

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!

2. HTML 實體編碼/解碼

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

3. 字元標準化(全形轉半形、移除控制字元)

$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

注意事項

  • 陣列模式下,鍵不能為空字串(會拋出警告)
  • 不支援正則表達式,需複雜模式用 `preg_replace()`
  • 多位元組字串(UTF-8 中文)正常支援,按字元而非位元組處理
copyright © 萬盛學電腦網 all rights reserved