substr_replace() 在字串指定位置替換指定長度的子字串,是字串精確手術刀。本文詳細說明語法、參數、邊界情況與實務應用模式。
<?php
substr_replace(
string|array $string, // 輸入字串或陣列
string|array $replace, // 替換字串或陣列
int|array $offset, // 起始位置(負數=從結尾算起)
int|array $length = null // 替換長度(負數=從結尾算起,省略=到結尾)
): string|array
<?php $string = "Warning: System will shutdown in NN minutes!"; // 找到 "NN" 位置 $pos = strpos($string, "NN"); // 30 // 替換 2 個字元為 "15" echo substr_replace($string, "15", $pos, 2) . "\n"; // Warning: System will shutdown in 15 minutes! // 模擬 10 分鐘後更新 sleep(10); // 實際應用用排程或快取時間戳 echo substr_replace($string, "5", $pos, 2) . "\n"; // Warning: System will shutdown in 5 minutes! // 更多範例 $str = "abcdef"; // 從位置 2 替換 3 字元 echo substr_replace($str, "XYZ", 2, 3) . "\n"; // abXYZf // 從位置 2 替換到結尾 echo substr_replace($str, "XYZ", 2) . "\n"; // abXYZ // 負數 offset:從結尾倒數 echo substr_replace($str, "XYZ", -3, 2) . "\n"; // abcXYf // 負數 length:保留結尾幾字元 echo substr_replace($str, "XYZ", 1, -1) . "\n"; // aXYZf ?>
<?php
$strings = ['apple', 'banana', 'cherry'];
$replace = ['X', 'Y', 'Z'];
$offset = [1, 2, 0];
$length = [2, 3, 1];
$result = substr_replace($strings, $replace, $offset, $length);
print_r($result);
/*
Array
(
[0] => aXple (apple: 位置1長度2替換為X)
[1] => baYna (banana: 位置2長度3替換為Y)
[2] => Zherry (cherry: 位置0長度1替換為Z)
)
*/
?>
<?php
function maskString(string $str, int $visibleStart = 4, int $visibleEnd = 4, string $maskChar = '*'): string {
$len = strlen($str);
if ($len <= $visibleStart + $visibleEnd) return $str;
$maskLength = $len - $visibleStart - $visibleEnd;
return substr_replace($str, str_repeat($maskChar, $maskLength), $visibleStart, $maskLength);
}
echo maskString('4242424242424242') . "\n"; // 4242********4242
echo maskString('A123456789', 1, 1) . "\n"; // A*******89
echo maskString('0912345678', 3, 2) . "\n"; // 091*****78
?>
<?php
function truncate(string $str, int $maxLength, string $ellipsis = '...'): string {
if (mb_strlen($str) <= $maxLength) return $str;
// 保留 ellipsis 空間
$truncateAt = $maxLength - mb_strlen($ellipsis);
if ($truncateAt <= 0) return $ellipsis;
// 找最後一個空白避免截斷單字
$truncated = mb_substr($str, 0, $truncateAt);
$lastSpace = mb_strrpos($truncated, ' ');
if ($lastSpace !== false && $lastSpace > $truncateAt * 0.7) {
$truncated = mb_substr($truncated, 0, $lastSpace);
}
return $truncated . $ellipsis;
}
echo truncate("這是一個很長的標題需要被截斷顯示", 15);
// 這是一個很長的...
?>
<?php
function renderTemplate(string $template, array $data): string {
$result = $template;
$offset = 0;
// 找所有 {{key}} 佔位符
while (preg_match('/\{\{(\w+)\}\}/', $result, $match, PREG_OFFSET_CAPTURE, $offset)) {
$key = $match[1][0];
$fullMatch = $match[0][0];
$pos = $match[0][1];
$len = strlen($fullMatch);
$replacement = $data[$key] ?? '';
$result = substr_replace($result, $replacement, $pos, $len);
// 更新 offset 避免無限迴圈
$offset = $pos + strlen($replacement);
}
return $result;
}
$template = "Hello {{name}}, welcome to {{site}}!";
echo renderTemplate($template, ['name' => 'John', 'site' => 'Example.com']);
// Hello John, welcome to Example.com!
?>
<?php
function fixedWidthFields(array $fields, array $widths): string {
$result = '';
foreach ($fields as $i => $field) {
$width = $widths[$i] ?? 10;
$field = substr($field, 0, $width); // 截斷過長
$result .= str_pad($field, $width); // 補齊寬度
}
return $result;
}
// 使用 substr_replace 版本(原地修改緩衝區)
function formatRecord(array $data, array $widths): string {
$buffer = str_repeat(' ', array_sum($widths));
$pos = 0;
foreach ($data as $i => $value) {
$width = $widths[$i] ?? 10;
$value = substr($value, 0, $width);
$buffer = substr_replace($buffer, $value, $pos, min(strlen($value), $width));
$pos += $width;
}
return $buffer;
}
echo formatRecord(['ID', 'Name', 'Email'], [5, 20, 30]);
?>
<?php
function removeMiddle(string $str, int $start, int $length): string {
return substr_replace($str, '', $start, $length);
}
$text = "The quick brown fox jumps over the lazy dog";
echo removeMiddle($text, 10, 10); // The quick over the lazy dog
?>
| 情況 | 行為 | 建議 |
|---|---|---|
$offset > strlen($string) | 在字串末尾附加 $replace | 預先檢查或使用 min($offset, strlen($string)) |
$offset < 0 且 abs($offset) > strlen() | 視為位置 0 | 同上 |
$length < 0 導致負長度 | 從結尾保留 abs($length) 字元 | 理解負數語意:保留結尾而非刪除 |
$replace 為陣列但 $string 為字串 | 只使用 $replace[0] | 確保類型一致 |
| 多位元組字元 | 按位元組操作,會破壞 UTF-8 字元 | 使用 mb_substr + 重組,或 grapheme_* |
<?php
function mb_substr_replace(string $string, string $replace, int $offset, int $length = null, string $encoding = 'UTF-8'): string {
$len = mb_strlen($string, $encoding);
// 正規化 offset
if ($offset < 0) $offset = max(0, $len + $offset);
$offset = min($offset, $len);
// 正規化 length
if ($length === null) {
$length = $len - $offset;
} elseif ($length < 0) {
$length = max(0, $len - $offset + $length);
} else {
$length = min($length, $len - $offset);
}
$prefix = mb_substr($string, 0, $offset, $encoding);
$suffix = mb_substr($string, $offset + $length, $len, $encoding);
return $prefix . $replace . $suffix;
}
echo mb_substr_replace('你好世界', 'PHP', 2, 2); // 你好PHP
?>
mb_substr_replace 封裝