萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 移除字串最後一個字元:substr、rtrim 兩種做法比較

常見需求:去除字串尾部的特定字元(如逗號、分號、換行)。

方法一:substr 截取

<?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);
?>

方法二:rtrim 移除尾部字元集合

<?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 參數速查

substr($str, $start, $length)
$start >= 0: 從開頭算起;$start < 0: 從結尾算起
$length > 0: 取該長度;$length < 0: 從結尾倒數略過長度
copyright © 萬盛學電腦網 all rights reserved