如何在 PHP 中刪除字串中的最後一個字元

Minahil Noor 2023年1月30日 PHP PHP String
  1. 使用 rtrim() 函式來刪除最後一個字元
  2. 使用 substr() 函式來刪除最後一個字元
如何在 PHP 中刪除字串中的最後一個字元

本文將介紹在 PHP 中使用函式 rtrim()substr() 從字串中刪除最後一個字元的不同方法。

使用 rtrim() 函式來刪除最後一個字元

rtrim() 函式明確用於刪除字串末尾的空格或字元。使用該函式的正確語法如下。

rtrim($string, $character);

內建函式 rtrim() 有兩個引數,每個引數的細節如下。

引數 說明
$string 強制 這是我們要刪除最後一個字元的字串
$character 可選 就是我們要從最後刪除的字元

這個函式返回執行刪除後得到的最終字串。下面的程式顯示了我們如何使用 rtrim() 函式從一個字串中刪除最後一個字元。

<?php
$mystring = "This is a PHP program.";
echo("This is the string before removal: $mystring\n");
$newstring = rtrim($mystring, ". ");
echo("This is the string after removal: $newstring");
?>

輸出:

This is the string before removal: This is a PHP program.
This is the string after removal: This is a PHP program

使用 substr() 函式來刪除最後一個字元

在 PHP 中,我們還可以使用 substr() 函式來刪除字串中的最後一個字元。這個命令返回一個指定的子字串,正確的執行語法如下。

substr($string, $start, $length)

函式 substr() 接受三個引數。

引數 說明
$string 強制 這是我們要刪除最後一個字元的字串
$start 強制 它是子字串的起始位置。你可以閱讀更多關於它的資訊這裡
$length 可選 如果給定值,那麼函式將返回從 $start 引數到指定長度的子字串。

使用 substr() 函式從字串中刪除最後一個字元的程式如下。

<?php
$mystring = "This is a PHP program.";
echo substr($mystring, 0, -1);
?>

輸出:

This is a PHP program
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

相關文章 - PHP String