php method to remove spaces at both ends of a string: 1. Directly use the trim() function to remove spaces at both ends. This function can remove blank characters or other predefined characters on both sides of the string. The syntax "trim (string)"; 2. Use the trtrim() and ltrim() functions to remove blank characters or other predefined characters on the right and left sides of the string respectively. The syntax is "rtrim(ltrim(string))".
The operating environment of this article: windows10 system, php8, thinkpad t480 computer.
In PHP, you can use the trim function or rtrim() ltrim() function to remove spaces at both ends of a string.
Method 1: Use the trim() function
The trim() function removes whitespace characters or other predefined characters on both sides of a string.
Syntax:
trim(string,charlist)
Example:
Remove spaces at both ends of the string
<?php <?php header("Content-type:text/html;charset=utf-8"); $str = " Hello World "; echo "原字符串:" . $str."!"; echo "<br>"; echo "去除空格后的字符串: " . trim($str)."!"; ?>
Method 2: Use the trtrim() ltrim() function
rtrim() function removes blank characters or other predefined characters on the right side of the string.
#ltrim() function removes whitespace characters or other predefined characters on the left side of a string.
Method: First use rtrim() to remove the spaces on the right, then use ltrim() to remove the spaces on the left
<?php header("Content-type:text/html;charset=utf-8"); $str = " Hello "; echo "原字符串:" . $str."!"; echo "<br>"; echo "去除空格后的字符串: " . rtrim(ltrim($str))."!"; ?>
Related Recommended: php tutorial
The above is the detailed content of How to remove spaces at both ends of string in php. For more information, please follow other related articles on the PHP Chinese website!