萬盛學電腦網

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

PHP 字串替換實戰:str_replace() 與 substr() 組合技巧

情境:更換圖片 URL 域名/路徑

<?php
$newpic = 'https://upload.111cn.net/';
$oldpic = 'https://down.111cn.net/uploads/';
$litpic = 'https://down.111cn.net/uploads/allimg/101124/1_21292911l.jpg';

// 方法一:str_replace 直接替換(推薦,語意清晰)
$litpic = str_replace($oldpic, $newpic, $litpic);
// 結果:https://upload.111cn.net/allimg/101124/1_21292911l.jpg

// 方法二:substr 截取後綴再拼接(舊寫法)
// $litpic = $newpic . substr($litpic, strlen($oldpic));

echo $litpic;
?>

str_replace() 完整語法

mixed str_replace(mixed $search, mixed $replace, mixed $subject, int &$count = null)
  • $search:搜尋目標(字串或陣列)
  • $replace:替換值(字串或陣列)
  • $subject:目標字串/陣列
  • $count:傳址參數,返回替換次數

進階用法:陣列批次替換

$text = '文章內容包含 [site_name] 和 [site_url]';

$search = ['[site_name]', '[site_url]'];
$replace = ['我的網站', 'https://example.com'];

$result = str_replace($search, $replace, $text);
// 文章內容包含 我的網站 和 https://example.com

// 計算替換次數
$count = 0;
$result = str_replace($search, $replace, $text, $count);
echo "共替換 $count 處";

substr() 截取字串

string substr(string $string, int $offset, int $length = null)
  • $offset ≥ 0:從開頭算起;< 0:從結尾倒數
  • $length > 0:最大長度;< 0:結尾省略長度;省略:到字串結尾
$str = 'abcdefgh';

substr($str, 2);        // cdefgh(從索引 2 到結尾)
substr($str, 2, 3);     // cde(從 2 起取 3 字元)
substr($str, -3);       // fgh(倒數 3 字元)
substr($str, 0, -2);    // abcdef(去掉最後 2 字元)

str_replace vs substr 選擇指南

場景推薦函數理由
已知完整舊字串,欲替換為新字串str_replace()語意明確、支援陣列批次、自動處理多處出現
固定前綴/路徑替換,效能極度敏感substr() + 拼接避免搜尋開銷,但需確定前綴長度固定
需驗證前綴確實存在才替換strncmp() + substr()先比對前 N 字元,再截取替換
複雜模式替換(正則)preg_replace()支援正則表達式、回呼函數

安全替換:確認前綴存在

function replace_prefix($string, $old_prefix, $new_prefix) {
    $len = strlen($old_prefix);
    if (strncmp($string, $old_prefix, $len) === 0) {
        return $new_prefix . substr($string, $len);
    }
    return $string;  // 前綴不符,不替換
}

$url = 'https://down.111cn.net/uploads/img.jpg';
echo replace_prefix($url, 'https://down.111cn.net/uploads/', 'https://cdn.new.com/');
// https://cdn.new.com/img.jpg

$url2 = 'https://other.com/img.jpg';
echo replace_prefix($url2, 'https://down.111cn.net/uploads/', 'https://cdn.new.com/');
// https://other.com/img.jpg(不變)

效能補充

  • `str_replace()` 內部優化極好,一般情況比 `preg_replace()` 快 3-5 倍
  • 大量字串替換時,單次 `str_replace($arr_search, $arr_replace, $str)` 比迴圈多次呼叫快
  • PHP 8+ `str_contains()`、`str_starts_with()`、`str_ends_with()` 可先快速判斷再替換
copyright © 萬盛學電腦網 all rights reserved