PHP function trim() that removes whitespace characters or other predefined characters on both sides of a string

黄舟
Release: 2023-03-17 07:16:01
Original
2229 people have browsed it

Example

Remove the characters on the left side of String ("He" in "Hello" and "d!" in "World"):

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

Definition and Usage

trim() function removes whitespace characters or other predefined characters on both sides of a string.

Related functions:

  • ltrim() - Removes whitespace characters or other predefined characters on the left side of a string.

  • rtrim() - Removes whitespace characters or other predefined characters on the right side of the string.

Syntax

trim(string,charlist)
Copy after login
##Technical details
ParametersDescription
string Required. Specifies the string to check.
charlist Optional. Specifies which characters are removed from the string. If this parameter is omitted, all the following characters are removed:
  • "\0" - NULL

  • ##"\t" - TAB
  • "\n" - Line feed
  • "\x0B" - Vertical tab character
  • "\ r" - Enter
  • " " - Space

Return value: Return the modified string. PHP Version: 4+##Update Log :
In PHP 4.1, the charlist parameter was added.

更多实例

实例 1

移除字符串两侧的空格:

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

上面代码的 HTML 输出如下(查看源代码):

<!DOCTYPE html>
<html>
<body>

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

上面代码的浏览器输出如下:

Without trim: Hello World!
With trim: Hello World!
Copy after login
Copy after login

实例 2

移除字符串两侧的换行符(\n):

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

上面代码的 HTML 输出如下(查看源代码):

<!DOCTYPE html>
<html>
<body>

Without trim:


Hello World!


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

上面代码的浏览器输出如下:

Without trim: Hello World!
With trim: Hello World!
Copy after login
Copy after login

例子

<?php 
$str = "##使用函数trim去掉字符串两端特定字符####"; 
$str1 = trim($str,"#"); 
//为函数trim传入第二个参数,
trim将删除字符串$str两端的#字符 echo $str."<br>"; 
echo $str1; 
?>
Copy after login

输出:

##使用PHP函数trim()去掉字符串两端特定字符#### 使用函数trim去掉字符串两端特定字符


The above is the detailed content of PHP function trim() that removes whitespace characters or other predefined characters on both sides of a string. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template