Home  >  Article  >  Backend Development  >  PHP example code for removing leading and trailing spaces from a string

PHP example code for removing leading and trailing spaces from a string

怪我咯
怪我咯Original
2017-07-07 10:17:421510browse

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 functiontrim. It is really much more convenient. I would like to share it

The first method: through the function that comes with php

<?php 
/* 
trim 去除一个字符串两端空格, 
rtrim 是去除一个字符串右部空格, 
ltrim 是去除一个字符串左部空格。 

*/ 
?> 
<?php 
echo trim(" 空格 ")."<br>"; 
echo rtrim(" 空格 ")."<br>"; 
echo ltrim(" 空格 ")."<br>"; 
?>

The second method: through regular expressionreplacement, with stronger function
php Remove leading and trailing spaces from the string (including full-width spaces)

The code is as follows:

<? 
$str="     PHP中文网www.php.cn    "; 
$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); 
?>

The above is the detailed content of PHP example code for removing leading and trailing spaces from a string. 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