Home >Backend Development >PHP Tutorial >PHP function trim() that removes whitespace characters or other predefined characters on both sides of a string

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

黄舟
黄舟Original
2017-11-06 13:46:512336browse

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!");
?>

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)
##Technical details
Parameters Description
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);
?>

上面代码的 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!

例子

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

输出:

##使用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!

Statement:
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