萬盛學電腦網

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

PHP substr_replace() 從指定位置替換字串完整教學

函數語法

string substr_replace(string $string, string $replace, int $start [, int $length ])
參數說明
$string原字串(必填)
$replace替換字串(必填)
$start起始位置(必填):正數=從開頭算起,負數=從結尾倒數,0=第一個字元
$length替換長度(選填):正數=替換字元數,負數=保留結尾字元數,0=插入不替換

基本範例

<?php
$str = "hello world";

// 從索引 6 開始替換到結尾
echo substr_replace($str, "earth", 6);       // hello earth

// 替換長度 5 個字元
echo substr_replace($str, "earth", 6, 5);    // hello earth

// 負數 start:從結尾倒數
echo substr_replace($str, "PHP", -6);        // hello PHP

// length=0:插入不刪除
echo substr_replace($str, " beautiful", 5, 0); // hello beautiful world

// 負數 length:保留結尾 N 字元
echo substr_replace($str, "PHP", 0, -6);     // PHP world
?>

進階:多筆一次替換(陣列參數)

PHP 支援將 $replace、$start、$length 設為陣列,對應處理多筆替換:

<?php
$str = "A quick brown fox";
$replace = ["slow", "red"];
$start = [2, 12];
$length = [5, 5];

echo substr_replace($str, $replace, $start, $length); // A slow red fox
?>

實務應用:遮罩敏感資訊

<?php
function maskString($str, $visibleStart = 3, $visibleEnd = 2, $maskChar = '*') {
    $len = strlen($str);
    if ($len <= $visibleStart + $visibleEnd) return $str;
    $maskLen = $len - $visibleStart - $visibleEnd;
    return substr_replace($str, str_repeat($maskChar, $maskLen), $visibleStart, $maskLen);
}

echo maskString("1234567890");       // 123****890
echo maskString("user@example.com"); // use******mple.com
echo maskString("0912345678", 3, 2); // 091****678
?>

實務應用:模板佔位符替換

<?php
function renderTemplate($template, $data) {
    foreach ($data as $key => $value) {
        $placeholder = "{{$key}}";
        $pos = strpos($template, $placeholder);
        if ($pos !== false) {
            $template = substr_replace($template, $value, $pos, strlen($placeholder));
        }
    }
    return $template;
}

$tpl = "親愛的 {{name}},您的訂單 {{order_id}} 已出貨。";
echo renderTemplate($tpl, ['name' => '小明', 'order_id' => '20240523001']);
// 親愛的 小明,您的訂單 20240523001 已出貨。
?>

與相關函數比較

函數用途典型場景
substr_replace()指定位置/長度替換/插入遮罩、模板、固定格式修改
str_replace()搜尋字串替換(全部)關鍵字替換、過濾
preg_replace()正規表示式替換複雜模式、資料清洗
copyright © 萬盛學電腦網 all rights reserved