Rumah  >  Artikel  >  pembangunan bahagian belakang  >  php trim函数怎么用

php trim函数怎么用

藏色散人
藏色散人asal
2019-05-29 11:35:522842semak imbas

php trim函数用于移除字符串两侧的空白字符或其他预定义字符,其语法是trim(string,charlist),参数string 必需。规定要检查的字符串。

php trim函数怎么用

php trim函数怎么用?

定义和用法

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!

实例 3

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

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

输出:

Hello World!
llo Worl

Atas ialah kandungan terperinci php trim函数怎么用. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:php number_format函数怎么用Artikel seterusnya:php min函数怎么用?