Home >Backend Development >PHP Tutorial >Multiple ways to remove spaces in strings in php_PHP Tutorial
This tutorial provides several php tutorials. There are many ways to delete spaces in strings. Use php functions, str_replace, trim, regular and other effective methods to replace spaces in strings
Use the functions that come with php
str_replace( " ", " ",$str);
to replace
$str = "##Use function trim to remove specific characters at both ends of the string####";
$str1 = trim($str,"#"); //Pass in the second parameter to the function trim. Trim will delete the # characters
at both ends of the string $str. echo $str."
";
echo $str1;
?>
Example
$str = "Use the trim function to remove blank characters at both ends of the string";
$str1 = trim($str); echo "There are ".strlen($str)." characters before processing";
echo "
";
echo "
";
echo "After using the trim function, there are ".strlen($str1)." characters";
?>
Look at a more advanced one
PHP program deletes "spaces" in "string elements" in "array"
$arr=array();
$arr[]="ad dfd dfd";
$arr[]="saf sdf dsf";
$arr[]="sdf dsfgfd dd";
$arr[]="dfd dfferw ";
while(list($name,$value)=each($arr)){
echo $value;
$arr2[]=trim($value);//Remove spaces
}
print_r($arr2);//This should be the array you want~
?>
Try to remove spaces using regular expressions
$string = preg_replace("/s+([rn$])/", "1", $string);
when "$" is inside [], www.45it.net does not represent the end of string
-------------------------------------------------- -------------
$string = preg_replace("/s+([x20]|$)/", "1", $string);
-------------------------------------------------- -------------
$string = preg_replace("/x20+([rn]|$)/", "1", $string);
-------------------------------------------------- -------------
$string = preg_replace('/([rn])[s]+/', '1', $string);