2010-11-18 18 views
2

我想檢查,如果$ _ POST [味精]包含長度超過30個字符(不含無空格)一個字,所以你不會是能寫:PHP:字覈查30個字符

例1:

asdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsddsasdsdsdsdsd

例2: 你好我的名字是asdoksdosdkokosdkosdkodskodskodksosdkosdkokodsdskosdkosdkodkoskosdkosdkosdkosdsdksdoksd

(注意沒有SP ACES)。

我該怎麼做?

回答

2

你可以使用preg_match尋找那些如下...

if (preg_match('/\S{31,}/', $_POST['msg'])) 
{ 
    //string contains sequence of non-spaces > 30 chars 
} 

的/ S匹配任何非空格字符,並且是相匹配的任何空間/秒倒數。查看PCRE escape sequences

+2

''\ S]'毫無意義。你可能忘記從'[^ \ s]' – 2010-11-18 09:00:57

+1

改變時忘記刪除'[]' - 我個人習慣否定\ s而不是\ s,但認爲使用\ S - 將編輯 – 2010-11-18 09:04:34

-1

首先拆分輸入單詞:

explode(" ", $_POST['msg']); 

然後得到最大長度的字符串:

max(explode(" ", $_POST['msg'])); 

,看看是否大於30:

strlen(max(explode(" ", $_POST['msg']))) > 30 
+1

-1表示語法上和語義上無效 – 2010-11-18 09:03:27

+0

現在是否正確@Paul? – 2010-11-18 09:06:50

+0

不,我認爲你的大腦的Python方面正在與PHP方面爭鬥。測試你的解決方案,你會明白我的意思。 – 2010-11-18 09:13:44

0

首先找到文字:

// words are separated by space usually, add more logic here 
$words = explode(' ', $_POST['msg']); 

foreach($words as $word) { 
    if(strlen($word) > 30) { // if the word is bigger than 30 
     // do something 
    } 
} 
+0

對於一個字符串不只幾個字,這是一個相當浪費的方法。 PHP會給你構建一個你並不需要的數組的麻煩。對於更長的字符串,正則線性掃描字符串的正則表達式或其他方法將具有更高的速度和空間效率。 – 2010-11-18 09:32:11

2

手冊頁面您可以使用正則表達式\w{31,}找到擁有31個或更多字符的一句話:如果你想找到的非空格字符是組

if(preg_match('/\w{31,}/',$_POST['msg'])) { 
     echo 'Found a word >30 char in length'; 
} 

31或更多字符的長度,你可以使用:

if(preg_match('/\S{31,}/',$_POST['msg'])) { 
     echo 'Found a group of non-space characters >30 in length'; 
} 
+1

我認爲我更喜歡你的答案。 – 2010-11-18 09:01:21

0

這個怎麼樣?邏輯上的區別

if (strlen(preg_replace('#\s+#', '', $_POST['msg'])) > 30) { 
    //string contain more then 30 length (spaces aren't counted) 
}