PHP trim () function
Examples
Remove the left side of the character string ( "Hello" in the "He" and "World" in the "d!"):
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
Running instance »
Definition and Usage
trim () function removes both sides of a string of blank characters or other predefined characters.
Related functions:
- LTRIM () - Remove the left side of a string of blank characters or other predefined characters.
- RTRIM () - remove the right of a string of blank characters or other predefined characters.
grammar
trim( string,charlist )
参数 | 描述 |
---|---|
string | 必需。规定要检查的字符串。 |
charlist | 可选。规定从字符串中删除哪些字符。如果省略该参数,则移除下列所有字符:
|
technical details
return value: | Returns the modified string. |
---|---|
PHP version: | 4+ |
Update log: | In PHP 4.1, add the charlist parameters. |
More examples
Example 1
Remove string of spaces on both sides:
<?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 output of the code above is as follows (view source):
<!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>
Browser output of the code above is as follows:
Without trim: Hello World!
With trim: Hello World!
With trim: Hello World!
Running instance »
Example 2
Remove strings on both sides of line breaks (\ 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 output of the code above is as follows (view source):
<!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>
Browser output of the code above is as follows:
Without trim: Hello World!
With trim: Hello World!
With trim: Hello World!
Running instance »
PHP String Reference