PHP trim() funktion
Exempel
Ta bort tecken från båda sidor av stringen ("Hello"-texten "He" samt "World"-texten "d!":)
<?php $str = "Hello World!"; echo $str . "<br>"; echo trim($str,"Hed!"); ?>
Definition och användning
trim()-funktionen tar bort tomma tecken på båda sidor av stringen eller andra fördefinierade tecken.
Relaterade funktioner:
Syntax
trim(s tring,charlist)
Parameter | Beskrivning |
---|---|
string | Nödvändigt. Anger den string som ska kontrolleras. |
charlist |
可选。规定从字符串中删除哪些字符。如果被省略,则移除以下所有字符:
|
技术细节
返回值: | 返回被修改的字符串 |
PHP 版本: | 4+ |
更新日志: | 在 PHP 4.1 中,新增了 charlist 参数。 |
更多实例
例子 1
移除字符串两侧的空格:
<?php $str = " Hello World! "; echo "不使用 trim: " . $str; echo "<br>"; echo "使用 trim: " . trim($str); ?>
以上代码的 HTML 输出如下(请查看源代码):
<!DOCTYPE html> <html> <body> 不使用 trim: Hello World! <br>使用 trim: Hello World! </body> </html>
以上代码的浏览器输出如下:
不使用 trim: Hello World! 使用 trim: Hello World!
例子 2
移除字符串两侧的换行符(\n):
<?php $str = "\n\n\nHello World!\n\n\n"; echo "不使用 trim: " . $str; echo "<br>"; echo "使用 trim: " . trim($str); ?>
以上代码的 HTML 输出如下(请查看源代码):
<!DOCTYPE html> <html> <body> 不使用 trim: Hello World! <br>使用 trim: Hello World! </body> </html>
以上代码的浏览器输出如下:
不使用 trim: Hello World! 使用 trim: Hello World!