查詢

substr_replace()函式—用法及示例

「 將字串的一部分替換為另一個字串 」


函式名:substr_replace()

函式描述:substr_replace() 函式用於將字串的一部分替換為另一個字串。

引數:

  • string:必需。原始字串。
  • replacement:必需。替換字串。
  • start:必需。替換的起始位置。如果 start 是正數,則從字串的 start 位置開始替換。如果是負數,則從字串末尾的 start 位置開始替換。
  • length:可選。替換的長度。如果省略,則替換從 start 位置開始到字串末尾的所有字元。
  • encoding:可選。指定字元編碼。常用的編碼有 "UTF-8"、"ISO-8859-1" 等。

返回值:返回替換後的字串。

示例:

$str = "Hello, world!";
$replacement = "PHP";
$start = 7;

// 替換字串的一部分為 "PHP"
$result = substr_replace($str, $replacement, $start);
echo $result; // 輸出 "Hello, PHP!"

$str2 = "Hello, world!";
$replacement2 = "PHP";
$start2 = -6;
$length2 = 5;

// 替換字串的一部分為 "PHP",從倒數第6個字元開始,替換長度為5
$result2 = substr_replace($str2, $replacement2, $start2, $length2);
echo $result2; // 輸出 "Hello, PHP!"

$str3 = "Hello, world!";
$replacement3 = "PHP";
$start3 = 7;
$length3 = 5;

// 替換字串的一部分為 "PHP",從第7個字元開始,替換長度為5
$result3 = substr_replace($str3, $replacement3, $start3, $length3);
echo $result3; // 輸出 "Hello, PHP, world!"

注意:substr_replace() 函式在 PHP 5 及以上版本可用。

補充糾錯
上一個函式: SVM::getOptions()函式
下一個函式: substr_count()函式
熱門PHP函式
分享連結