How to remove leading and trailing spaces in php

藏色散人
Release: 2023-03-04 09:06:01
Original
3992 people have browsed it

How to remove leading and trailing spaces in php: 1. Remove spaces through the "trim", "rtrim" and "ltrim" functions that come with PHP; 2. Replace and remove spaces through regular expressions, the syntax is as follows "mb_ereg_replace('^( | ) ', '', $str);".

How to remove leading and trailing spaces in php

Recommended: "PHP Video Tutorial"

How to remove spaces at the beginning and end of a string in PHP

When I was doing PHP today, I needed to remove the spaces at the beginning and end of the string. Baidu found out that PHP comes with this function trim, which is really much more convenient. I would like to share it with you

The first method: through the function that comes with php

<?php
/*
trim 去除一个字符串两端空格,
rtrim 是去除一个字符串右部空格,
ltrim 是去除一个字符串左部空格。
*/
?>
<?php
echo trim(" 空格 ")."<br>";
echo rtrim(" 空格 ")."<br>";
echo ltrim(" 空格 ")."<br>";
?>
Copy after login

The second method: through regular expression replacement, the function is stronger

php removes the leading and trailing spaces in the string (including Full width)

The code is as follows:

<?
$str="     脚本之家 www.jb51.net     ";
$str = mb_ereg_replace(&#39;^( | )+&#39;, &#39;&#39;, $str);
$str = mb_ereg_replace(&#39;( | )+$&#39;, &#39;&#39;, $str);
echo mb_ereg_replace(&#39;  &#39;, "\n  ", $str);
?>
Copy after login

The above is the detailed content of How to remove leading and trailing spaces in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!