PHP to remove the first and last Spaces from a string

  • 2020-05-17 04:50:50
  • OfStack

Method 1: via php's built-in functions
< ?php
/*
trim strips 1 string of Spaces,
rtrim is to remove the space on the right of a string,
ltrim is to remove the left space from a string.

*/
? >
< ?php
echo trim(" space ")." < br > ";
echo rtrim(" space ")." < br > ";
echo ltrim(" space ")." < br > ";
? >
The second method is more powerful through regular expression substitution
php removes Spaces at the beginning and end of a string (including full corners)
 
<? 
$str="     The home of the script  www.ofstack.com     "; 
$str = mb_ereg_replace('^( | )+', '', $str); 
$str = mb_ereg_replace('( | )+$', '', $str); 
echo mb_ereg_replace('  ', "\n  ", $str); 
?> 

Related articles: