首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 字串部分替換:substr_replace() 函數完整用法指南

     編輯:PHP 相關知識

前言

substr_replace() 可在字串指定位置、指定長度範圍內替換為新字串,比 str_replace() 更精確控制替換範圍。本文詳細說明參數、多重替換與實務範例。

函數簽名

substr_replace(
    string|array $string,
    string|array $replace,
    int|array $offset,
    int|array $length = null
): string|array

參數說明

  • $offset:起始位置(0 為開頭,負數從結尾倒數)。
  • $length:替換長度。0 為插入不刪除;正數刪除該長度;負數保留結尾該長度;null 替換到結尾。

基本範例:倒數計時訊息

<?php
$msg = "Warning: System will shutdown in NN minutes!";
$pos = strpos($msg, "NN");

echo substr_replace($msg, "15", $pos, 2) . "\n"; // Warning: System will shutdown in 15 minutes!
sleep(10); // 模擬 10 秒
echo substr_replace($msg, "5", $pos, 2) . "\n";  // Warning: System will shutdown in 5 minutes!
?>

進階用法

<?php
$str = "abcdef";

// 插入不刪除(length=0)
echo substr_replace($str, "XXX", 2, 0) . "\n"; // abXXXcdef

// 替換到結尾(length=null)
echo substr_replace($str, "XYZ", 2) . "\n";    // abXYZ

// 保留結尾 2 字元(length=-2)
echo substr_replace($str, "MID", 1, -2) . "\n"; // aMIDef

// 陣列批次處理
$arr = ["apple", "banana", "cherry"];
echo implode(", ", substr_replace($arr, "FRUIT_", 0, 0)) . "\n";
// FRUIT_apple, FRUIT_banana, FRUIT_cherry
?>

與 str_replace() 比較

總結

substr_replace() 以位置索引精確控制替換範圍,適合模板訊息、固定格式字串處理。掌握 $offset 與 $length 的正負數含義即可靈活運用。希望本文對您的 PHP 程式設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
特性substr_replace()str_replace()
定位方式位置索引搜尋字串
替換長度控制精確指定依搜尋字串長度
多重替換支援陣列參數支援陣列參數
適用場景固定格式模板、位置精確關鍵字替換、內容過濾