Home >Backend Development >PHP Problem >How to remove leading and trailing spaces from a string in php

How to remove leading and trailing spaces from a string in php

青灯夜游
青灯夜游Original
2021-05-10 16:11:133406browse

php method to remove spaces at the beginning and end of a string: 1. Use the trim() function to remove spaces at both ends of the string, the syntax is "trim (string)"; 2. Use rtrim() and ltrim() The function removes spaces on the right and left sides of the string respectively, with the syntax "rtrim(string)" and "ltrim(string)".

How to remove leading and trailing spaces from a string in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php remove string Leading and trailing spaces

Method 1: Use the trim() function

trim() function to remove whitespace characters or other prefixes on both sides of the string Define characters.

Example:

<?php
$str = " Hello World! ";
echo "原字符串:" . $str;
echo "<br>";
echo "去除空格后的字符串: " . trim($str);
?>

Output:

原字符串: Hello World!
去除空格后的字符串: Hello World!

Method 2: Using rtrim() and ltrim() functions

## The #rtrim() function removes whitespace characters or other predefined characters from the right side of a string.

ltrim() function removes whitespace characters or other predefined characters on the left side of a string.

Example:


<?php
$str = "Hello World! ";
echo "原字符串: " . $str;
echo "<br>";
echo "去除空格后的字符串: " . rtrim(ltrim($str));
?>

Output:


原字符串: Hello World!
去除空格后的字符串: Hello World!

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of How to remove leading and trailing spaces from a 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