Home  >  Article  >  Backend Development  >  How to remove spaces at both ends of string in php

How to remove spaces at both ends of string in php

王林
王林Original
2021-02-20 16:22:023570browse

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))".

How to remove spaces at both ends of string in php

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

How to remove spaces at both ends of string in php

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

How to remove spaces at both ends of string in php

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!

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