2009-11-18 67 views
5
print_r(strlen(trim('  '))); 

結果是9如何檢查PHP中是否只有字符串中的空格?

我也試過

preg_replace('/[\n\r\t\s]/', '', ' ') 

但結果不是零。

請下載我的代碼,你會得到的結果

http://blog.eood.cn/attachment.php?id=70

+3

你的兩次嘗試甚至沒有意義,也沒有你的結果。修剪第一個字符串應該產生一個空字符串(長度爲0)。 preg_replace用於替換字符串,而不檢查它們是否存在。 – mpen 2009-11-18 08:22:19

+0

對於標題中的錯誤感到抱歉。 – 2009-11-18 08:24:02

+2

@Bruce:在我的安裝中:'print_r(strlen(trim('')));'= 0想知道如何得到9! – RageZ 2009-11-18 08:24:58

回答

11
mb_language('uni'); 
mb_internal_encoding('UTF-8'); 

$s = '     '; 
if (strlen(preg_replace('/\s+/u','',$s)) == 0) { 
    echo "String is empty.\n"; 
} 

如果不工作,我建議這樣做

$s = '  '; 
if (strlen(trim(preg_replace('/\xc2\xa0/',' ',$s))) == 0) { 
    echo "String is empty.\n"; 
} 

這些解決方案已在不同的平臺上進行過測試。

在U flag講述的preg_replace()來處理字符串作爲一個多字節字符串,即UTF-8

的字符是一個不間斷空格C2A0,並且可以與ALT + 0160來生成。

+0

你可以下載我的代碼,並檢查*空間*,我認爲這不是正常的空間。 – 2009-11-18 08:43:48

+1

請注意'empty'也爲''0''返回* true *。 – Gumbo 2009-11-18 08:47:10

+0

請下載我的代碼 – 2009-11-18 08:52:58

0

你想知道一個字符串是否包含空格?

if(strpos($string, ' ') !== false) echo $string.' contains a space'; 
0

如何this ...

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

或者這...

$str = str_replace(array("\n", "\r", "\t", " ", "\o", "\xOB"), '', $str); 
+0

結果是2,而不是零 – 2009-11-18 08:28:39

2

我認爲,最快的方法就是修剪領先的空間(如果有其它字符ltrim將失敗快)和比較的結果爲空字符串:

# Check if string consists of only spaces 
if (ltrim($string, ' ') === '') { 
0
if(strlen(trim($_POST['foobar'])) == 0){ 
die('the user didn\'t input anything!'); 
} 

empty還將使

$bar = trim($_POST['foobar']); 
if(empty($bar)){ 
die('the user didn\'t input anything!'); 
} 
+0

我無法得到空的聲明運行,那有什麼關係? – 2009-11-18 08:36:01

+2

啊,你必須在使用空之前將修剪過的字符串賦給變量。 – 2009-11-18 08:38:03

+0

@彼得:好點! – RageZ 2009-11-18 08:47:11

3

中號你是否正在做其他事情搞亂了結果?您的測試返回0

print_r(strlen(trim('  '))); 

這就是trim的預期行爲。

該函數返回 從空白開始 和STR的端部剝離的字符串。沒有第二 參數,修剪()將去除這些 字符:

  • 「」(ASCII 32(0×20)),一個普通的空間。
  • 「\ t」(ASCII 9(0x09)),一個選項卡。
  • 「\ n」(ASCII 10(0x0A)),換行(換行)。
  • 「\ r」(ASCII 13(0x0D)),回車。
  • 「\ 0」(ASCII 0(0x00)),NUL字節。
  • 「\ x0B」(ASCII 11(0x0B)),一個垂直標籤。

UPDATE:

看你的連接代碼,我注意到你有2個空間之間的一個多餘的字符。

這是hexdump都可以輸出-C

$ hexdump -C space.php 
00000000 3c 3f 0d 0a 70 72 69 6e 74 5f 72 28 73 74 72 6c |<?..print_r(strl| 
00000010 65 6e 28 74 72 69 6d 28 27 20 c2 a0 20 27 29 29 |en(trim(' .. '))| 
00000020 29 3b 0d 0a 3f 3e         |);..?>| 
00000026 

這是OD輸出,與文件中只是性格。

$ od space.php 
0000000 120302               
0000002 

修剪不會刪除該空間,因爲..好吧,它不是空間。 This is a good reference關於如何識別不尋常的字符。

哦,爲了回答您更新的問題,只需使用empty,正如Peter所說。

2

一個簡單的preg_match()就足夠了:

if(preg_match('/^\s+$/', $str)) == 1){ 
die('there are only spaces!'); 
} 
0

如果裝飾($ VAR)沒有再工作$變種可能不是一個字符串。 所以首先鑄造到串

$ VAR1 =串($變種) 然後 修整(VAR1 $)