PHP trim() 函數

PHP String 參考手冊 PHP String 參考手冊

實例

移除字串左側的字元("Hello" 中的 "He"以及 "World" 中的 "d!"):

<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>


定義和用法

trim() 函數移除字串兩側的空白字元或其他預定義字元。

相關函數:

  • ltrim() - 移除字串左側的空白字元或其他預定義字元。
  • rtrim() - 移除字串右側的空白字元或其他預定義字元。

語法

trim(string,charlist)

參數 描述
string 必需。規定要檢查的字串。
charlist 可選。規定從字串中刪除哪些字元。如果省略該參數,則移除下列所有字元:
  • "\0" - NULL
  • "\t" - 跳位字元
  • "\n" - 換行
  • "\x0B" - 垂直跳位字元
  • "\r" - 回車
  • " " - 空格

技術細節

返回值: 返回已修改的字串。
PHP 版本: 4+
更新日誌: 在 PHP 4.1 中,新增了 charlist 參數。


更多實例

實例 1

移除字串兩側的空格:

<?php
$str = " Hello World! ";
echo "Without trim: " . $str;
echo "<br>";
echo "With trim: " . trim($str);
?>

上面代碼的 HTML 輸出如下(查看源代碼):

<!DOCTYPE html>
<html>
<body>

Without trim: Hello World! <br>With trim: Hello World!
</body>
</html>

上面代碼的流覽器輸出如下:

Without trim: Hello World!
With trim: Hello World!


實例 2

移除字串兩側的換行符(\n):

<?php
$str = "nnnHello World!nnn";
echo "Without trim: " . $str;
echo "<br>";
echo "With trim: " . trim($str);
?>

上面代碼的 HTML 輸出如下(查看源代碼):

<!DOCTYPE html>
<html>
<body>

Without trim:


Hello World!


<br>With trim: Hello World!
</body>
</html>

上面代碼的流覽器輸出如下:

Without trim: Hello World!
With trim: Hello World!



PHP String 參考手冊 PHP String 參考手冊