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

青灯夜游
Release: 2023-03-09 15:10:01
Original
3376 people have browsed it

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);
?>
Copy after login

Output:

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

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));
?>
Copy after login

Output:


原字符串: Hello World!
去除空格后的字符串: Hello World!
Copy after login
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template