Home > Article > Backend Development > How to remove spaces on both sides in php
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," ")".
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('^( | )+', '', $str); $str = mb_ereg_replace('( | )+$', '', $str); echo mb_ereg_replace(' ', "\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!