回答
,您可以嘗試這樣的:
$string = "this has way more than 5 words so we want to deny it ";
//edit: make sure only one space separates words if we want to get really robust:
//(found this regex through a search and havent tested it)
$string = preg_replace("/\\s+/", " ", $string);
//trim off beginning and end spaces;
$string = trim($string);
//get an array of the words
$wordArray = explode(" ", $string);
//get the word count
$wordCount = sizeof($wordArray);
//see if its too big
if($wordCount > 5) echo "Please make a shorter string";
應該工作:-)
你必須做兩次,使用在客戶端的JavaScript一次,然後使用PHP的服務器端。
你可以指望的空格數...
$wordCount = substr_count($input, ' ');
這不是['count_chars'](http://php.net/manual/en/function。count-chars.php),這個例子完全被破壞了。你甚至不會將字符串傳遞給函數。 – meagar 2010-10-20 02:42:42
根據微薄的評論編輯更正。 – 2010-10-20 02:56:28
如果$輸入你的輸入字符串,
$wordArray = explode(' ', $input);
if (count($wordArray) > 5)
//do something; too many words
雖然我真的不知道爲什麼你會想這樣做用php輸入驗證。如果您只是使用javascript,則可以在表單提交之前讓用戶有機會更正輸入內容。
使用PHP做輸入驗證是絕對必要的。 JavaScript可以並將在程序生命週期的正常過程中繞過。 – meagar 2010-10-20 02:33:12
它應該一起完成。 – 2010-10-20 02:58:44
如果你這樣做;
substr_count($_POST['your text box'], ' ');
它限制到4
在PHP中,使用分割功能通過space.So你把它分解會得到詞語的數組。然後檢查數組的長度。
$mytextboxcontent=$_GET["txtContent"];
$words = explode(" ", $mytextboxcontent);
$numberOfWords=count($words);
if($numberOfWords>5)
{
echo "Only 5 words allowed";
}
else
{
//do whatever you want....
}
我沒有測試this.Hope這個工程。我現在沒有在我的機器上設置PHP環境。
除了()或substr_count(),爲什麼不直接使用PHP的內置函數計算字符串中的單詞的數量。我知道這個功能名稱並不特別直觀,但:
$wordCount = str_word_count($string);
將是我的建議。
注意,在使用多字節字符集時,這是不一定很有效。在這種情況下,是這樣的:
define("WORD_COUNT_MASK", "/\p{L}[\p{L}\p{Mn}\p{Pd}'\x{2019}]*/u");
function str_word_count_utf8($str)
{
return preg_match_all(WORD_COUNT_MASK, $str, $matches);
}
建議的str_word_count()
手冊頁
我想你想先用javascript做到這一點,只允許用戶插入5個字(後與驗證它PHP,以避免不良意圖)
在JS,你需要爲你鍵入它們計數字符,並保持你寫的字計數(通過增加計數器每個空格)
看看這個代碼: http://javascript.internet.com/forms/limit-characters-and-words-entered.html
- 1. 如何限制輸入文本框允許只有0和1
- 2. 允許用戶只輸入文本?
- 3. 限制在文本框中允許的字符(輸入金額)
- 4. 如何限制輸入欄只允許*和0-9?
- 5. UITextField只允許英文字母輸入
- 6. 只允許在文本框中輸入數字
- 7. 只允許在WPF文本框中輸入數字
- 8. 如何只允許文本輸入的數字,但允許JavaScript的命令?
- 9. 只允許帶正文的文本輸入掩碼
- 10. 角度限制不允許在文本字段中輸入空格
- 11. 兩個只有一個輸入文本提交允許
- 12. 訪問輸入文本框,只有選擇啓用允許searchs
- 13. AngularJS問題只允許將數字輸入到文本框中
- 14. 輸入文本只允許3特定的字符
- 15. 輸入文本框字段只允許字符不允許數字,但允許空間?
- 16. 限制對文本框的輸入:僅允許數字和小數點
- 17. 表單輸入文本字段中允許的字符數限制
- 18. HTML文本輸入限制
- 19. 這是什麼意思,只允許預期的輸入在PHP?
- 20. HTML文本輸入不允許輸入文字
- 21. 只允許使用JavaScript輸入數字並允許複製和粘貼?
- 22. 如何只允許輸入字母?
- 23. 只允許輸入浮點數
- 24. 二維輸入只允許第一行
- 25. 限制用戶輸入0作爲第一個字符,但允許在文本框中輸入10
- 26. Angular2 - 只允許在輸入中輸入Alpha字符
- 27. 如何在Outlook VBA輸入框中只允許輸入數字
- 28. 如何限制數字鍵盤輸入只允許單個小數點
- 29. 只允許在iPhone中輸入英文字符UITextField
- 30. 限制輸入在編輯文本
你或許應該測試字符串的長度和空格數量像布萊恩展示了。如果你不測試總長度oneCanWriteAVeryLongTextThatCountsOnlyAsOneWordAndThatsProbablyNotWhatYouWant。 – some 2010-10-20 02:34:49