PHP trim() 函數
實例
移除字串左側的字元("Hello" 中的 "He"以及 "World" 中的 "d!"):
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
定義和用法
trim() 函數移除字串兩側的空白字元或其他預定義字元。
相關函數:
語法
trim(string,charlist)
參數 | 描述 |
---|---|
string | 必需。規定要檢查的字串。 |
charlist | 可選。規定從字串中刪除哪些字元。如果省略該參數,則移除下列所有字元:
|
技術細節
返回值: | 返回已修改的字串。 |
---|---|
PHP 版本: | 4+ |
更新日誌: | 在 PHP 4.1 中,新增了 charlist 參數。 |
更多實例
實例 1
移除字串兩側的空格:
<?php
$str = " Hello World! ";
echo "Without trim: " . $str;
echo "<br>";
echo "With trim: " . trim($str);
?>
$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>
<html>
<body>
Without trim: Hello World! <br>With trim: Hello World!
</body>
</html>
上面代碼的流覽器輸出如下:
Without trim: Hello World!
With 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);
?>
$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>
<html>
<body>
Without trim:
Hello World!
<br>With trim: Hello World!
</body>
</html>
上面代碼的流覽器輸出如下:
Without trim: Hello World!
With trim: Hello World!
With trim: Hello World!
