[英]How do I compress space characters with PHP regular expressions?
$string = 'Hello this is a bunch of numbers: 333 and letters and $pecial Characters@!*(';
$foo = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);
echo $foo;
以上回報:
Hello this is a bunch of numbers 333 and letters and pecial Characters
我想保留空間,但如果不止一個,則不能。 怎么辦?
它應該看起來像:
Hello this is a bunch of numbers 333 and letters and pecial Characters
$foo = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);
$foo = preg_replace('/\s+/',' ',$foo);
一個正則表達式會這樣做:
$foo = preg_replace('/[^a-zA-Z0-9\s]|(\s)\s+/', '$1', $string);
我沒有使用PHP,但在Perl中它是這樣的:
s/\s+/ /g
即用一個空格替換一個或多個空格的任何序列。
所以我想象壓縮空間的PHP將是:
$foo = preg_replace("/\s{2,}/", " ", $string);
我不認為運行兩個preg_replace行應該有任何問題,特別是如果它使代碼更清晰。
全局替換( 編輯測試):
/(?<=\\s)\\s+|[^a-zA-Z0-9\\s]+/
用“”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.