常見需求:去除字串尾部的特定字元(如逗號、分號、換行)。
<?php
$str = '1,2,3,4,5,6,';
$new = substr($str, 0, -1); // 負數長度 = 從結尾倒數
echo $new; // 1,2,3,4,5,6
// 等價寫法
$new = substr($str, 0, strlen($str) - 1);
?>
<?php
$str = '1,2,3,4,5,6,';
$new = rtrim($str, ','); // 僅移除尾部的逗號
echo $new; // 1,2,3,4,5,6
// 移除多種尾部字元
$new = rtrim($str, ",;\r\n");
?>
| 方法 | 行為 | 適用場景 |
|---|---|---|
| substr($str, 0, -1) | 無條件移除最後 1 個字元 | 確定尾部只有一個多餘字元 |
| rtrim($str, ',') | 移除尾部所有在字元集合中的字元 | 尾部可能有多個相同/不同分隔符 |
substr($str, $start, $length)
$start >= 0: 從開頭算起;$start < 0: 從結尾算起
$length > 0: 取該長度;$length < 0: 從結尾倒數略過長度