"]; 2. Replace with regular expressions, the code is [$str = mb_ereg_replace('(|)+$', '', $str]."/> "]; 2. Replace with regular expressions, the code is [$str = mb_ereg_replace('(|)+$', '', $str].">

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

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

coldplay.xixi
coldplay.xixiOriginal
2020-08-03 09:50:443648browse

How to remove the leading and trailing spaces of a string in PHP: 1. Use the function [trim] function, the code is [echo trim("space")."
"]; 2. Replace with regular expressions , the code is [$str = mb_ereg_replace('(|) $', '', $str].

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

First method: Pass PHP’s built-in function

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

The second method: replace with regular expression, more powerful

php removes spaces at the beginning and end of 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);
?>

Related learning recommendations:php graphic 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