回答
,您可以嘗試這樣的:
$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. 限制HTML輸入只允許粘貼
- 2. 如何限制輸入文本框允許只有0和1
- 3. 允許用戶只輸入文本?
- 4. 限制在文本框中允許的字符(輸入金額)
- 5. 文本輸入只允許在angularjs整數輸入
- 6. PHP只允許@,_, - 和。從輸入
- 7. 如何限制輸入欄只允許*和0-9?
- 8. 只允許輸入字母
- 9. 只允許數字輸入
- 10. UITextField只允許英文字母輸入
- 11. 只允許在文本框中輸入數字
- 12. 只允許在WPF文本框中輸入數字
- 13. PHP - 變量,只允許文本
- 14. 如何只允許文本輸入的數字,但允許JavaScript的命令?
- 15. 只允許帶正文的文本輸入掩碼
- 16. 角度限制不允許在文本字段中輸入空格
- 17. 由PHP限制文本框輸入值
- 18. HTML/PHP允許輸入文件允許導航上傳
- 19. 輸入框,允許富文本功能
- 20. 如何允許輸入多行文本?
- 21. AngularJS問題只允許將數字輸入到文本框中
- 22. 允許文本字段只輸入數字[Java]
- 23. 只允許範圍內的數字輸入到文本框
- 24. 訪問輸入文本框,只有選擇啓用允許searchs
- 25. 兩個只有一個輸入文本提交允許
- 26. 輸入文本只允許3特定的字符
- 27. 只允許文本輸入字段中的特定域
- 28. AngularJs輸入文本框只允許大於零的值
- 29. 允許空文本框,但不允許輸入無效
- 30. 輸入文本框字段只允許字符不允許數字,但允許空間?
你或許應該測試字符串的長度和空格數量像布萊恩展示了。如果你不測試總長度oneCanWriteAVeryLongTextThatCountsOnlyAsOneWordAndThatsProbablyNotWhatYouWant。 – some 2010-10-20 02:34:49