php怎么去除空格和換行符

PHP
小億
148
2024-03-14 15:53:28

要去除字符串中的空格和換行符,可以使用PHP的內(nèi)置函數(shù)str_replace()preg_replace()

  1. 使用str_replace()函數(shù)去除空格和換行符:
$str = "Hello World\n";
$str = str_replace(array("\n", " "), "", $str);
echo $str; // 輸出:HelloWorld
  1. 使用preg_replace()函數(shù)去除空格和換行符:
$str = "Hello World\n";
$str = preg_replace("/[\n\s]+/", "", $str);
echo $str; // 輸出:HelloWorld

以上兩種方法都可以去除字符串中的空格和換行符,選擇其中一種方法即可。

0