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

PHP substr_replace 字串替換實戰範例大全

     編輯:PHP 相關知識

函數簡介

substr_replace(string, replacement, start, length) 將字串從 start 位置、長度 length 的部分替換為 replacement。注意:中文字串需先處理編碼,否則會產生亂碼。

基本參數示範

$string1 = "123456789";

echo substr_replace($string1, '###', 0);        // ###
echo substr_replace($string1, '###', 5);        // 12345###
echo substr_replace($string1, '###', 0, 0);     // ###123456789
echo substr_replace($string1, '###', 8, -2);    // 12345678###9
echo substr_replace($string1, '###', -6, -1);   // 123###9
echo substr_replace($string1, '###', -1);       // 123###9
echo substr_replace($string1, '###', 1, -1);    // 1###9
echo substr_replace($string1, '###', 1, 1);     // 1###3456789

進階應用範例

1. 替換/插入/刪除指定片段

$var = 'ABCDEFGH:/MNRPQR/';
echo substr_replace($var, 'bob', 0);               // bob
echo substr_replace($var, 'bob', 0, strlen($var)); // bob
echo substr_replace($var, 'bob', 0, 0);            // bobABCDEFGH:/MNRPQR/
echo substr_replace($var, 'bob', 10, -1);          // ABCDEFGH:/bob/
echo substr_replace($var, 'bob', -7, -1);          // ABCDEFGH:/bob/
echo substr_replace($var, '', 10, -1);             // ABCDEFGH://  (刪除)

2. 過長字串中間用省略號縮略

$longString = 'abcdefghijklmnopqrstuvwxyz0123456789z.jpg';
$separator  = '...';
$maxlength  = 25 - strlen($separator);
$start      = $maxlength / 2;
$trunc      = strlen($longString) - $maxlength;

echo substr_replace($longString, $separator, $start, $trunc);
// 輸出:abcdefghijk...456789z.jpg

3. 保留單字完整的截斷函數

function truncate($text, $numb) {
    $text = html_entity_decode($text, ENT_QUOTES);
    if (strlen($text) > $numb) {
        $text = substr($text, 0, $numb);
        $text = substr($text, 0, strrpos($text, " "));
        if (substr($text, -1) == ".") {
            $text = substr($text, 0, strrpos($text, "."));
        }
        $text .= "...";
    }
    return htmlentities($text, ENT_QUOTES);
}

$text = 'welcome to nowamagic, welcome to nowamagic, welcome to nowamagic';
echo truncate($text, 35);
// 輸出:welcome to nowamagic, welcome...

常見陷阱提醒

  • 中文截斷:請改用 mb_substr_replace 或先轉 UTF-8 陣列處理。
  • start 為負數時從字串末尾倒數;length 為負數表示保留尾部字元數。
  • 若 length = 0 視為插入模式(不刪除原字元)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved