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!
運行實例»
PHP String參考手冊