Home  >  Article  >  Backend Development  >  How to remove spaces on both sides in php

How to remove spaces on both sides in php

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-05-27 17:25:573155browse

Method: 1. Use the mb_ereg_replace function to remove, the syntax format is "mb_ereg_replace(regular expression, '', $str)"; 2. Use the trim function to remove whitespace characters on both sides of the string, the syntax format is is "rtrim(string," ")".

How to remove spaces on both sides in php

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

The first method: through php’s own Function

trim() function removes whitespace characters or other predefined characters on both sides of a string.

<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>

The second method: replace by regular expression, more powerful
php removes spaces at the beginning and end of the string (including full-width)

<?php
$str="     hello world     "; 
$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); 
?>

Recommended: " Summary of PHP interview questions in 2021 (collection) 》《php video tutorial

The above is the detailed content of How to remove spaces on both sides 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