如何使用正則表達式(preg_replace)刪除字符串末尾處的多餘空格?PHP:使用正則表達式從字符串中刪除額外空間
$string = "some random text with extra spaces at the end ";
如何使用正則表達式(preg_replace)刪除字符串末尾處的多餘空格?PHP:使用正則表達式從字符串中刪除額外空間
$string = "some random text with extra spaces at the end ";
沒有必要正則表達式在這裏,你可以使用rtrim
它,它的清潔和更快:
$str = rtrim($str);
但是,如果你想有一個基於正則表達式的解決方案,您可以使用:
$str = preg_replace('/\s*$/','',$str);
正則表達式使用是/\s*$/
\s
是短期的任何空白 炭,其包括空間。*
是零個或更多 $
的量詞的端錨基本上我們替換後什麼也沒有(''
)空白字符,有效地刪除它們。
您可以使用rtrim
你並不真正需要的正則表達式,在這裏,你可以使用rtrim()功能。
$string = "some random text with extra spaces at the end ";
$string = rtrim($string);
參見:
您可以使用TRIM()來做到這一點:
你可以使用PHP的裝飾和的preg_replace這一點。
看到完整的例子點擊這個鏈接http://akhleshit.blogspot.com/2013/04/remove-extra-spaces-from-string-in-php.html
而不是'*'量詞,你可以使用'+'量詞來避免無所不用。 – Toto 2010-09-21 19:14:36
非常感謝你!字符信息非常感謝 – Zebra 2010-09-21 19:22:02
@ M42,謝謝! – Zebra 2010-09-21 19:24:39