PHP 去除特別字元

1,字串如下:

$str = " This line  contains\tliberal \r\n use of   whitespace.\n\n";

2.First remove the leading/trailing whitespace(去掉開始和結束的空白)

$str = trim($str);

3.Now remove any doubled-up whitespace(去掉跟隨別的擠在一塊的空白)

$str = preg_replace('/\s(?=\s)/', '', $str);

4.Finally, replace any non-space whitespace, with a space(最後,去掉非space 的空白,用一個空格代替)

$str = preg_replace('/[\n\r\t]/', ' ', $str);>/pre?

5.Echo out: ‘This line contains liberal use of whitespace.’

echo "<pre>{$str}</pre>";

 

上例一步一步的去掉所有的空白。

 

首先我們使用trim()函數來去掉開始和結束的空白。

 

然後,我們使用preg_replace() 去除重複的。\s代表任何whitespace 。(?=) 表示向前查找 。

它味著只匹配後面有和它本身相同字串的字符。所以這個正則表達式的意思是: “被whitespace 字符跟隨的任何whitespace 字符。” 我們用空白來替換掉,這樣也就去除了,留下的將是唯一的whitespace 字符。

 

最後, 我們使用另一個正則表達式[\n\r\t]來查找任何殘餘的換行符(\n), 回車(\r), 或製表符(\t) 。我們用一個空格來替換這些。

資料來源:https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/255480/