将 PHP 中的文本输入限制为仅允许五 (5) 个单词
我想知道如何使用 PHP 在文本输入中只允许五 (5) 个单词。
我知道我可以使用 strlen 函数进行字符计数,但我想知道如何对单词进行计数。
I want to know how I can allow only five (5) words on text input using PHP.
I know that I can use the strlen
function for character count, but I was wondering how I can do it for words.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
你可以这样尝试:
应该可以:-)
You can try it like this:
should work :-)
如果你这样做;
并将其限制为 4
If you do;
And limit it to 4
如果 $input 是您的输入字符串,
尽管我真的不知道您为什么要使用 php 进行输入验证。如果您只使用 javascript,则可以在表单提交之前让用户有机会更正输入。
If $input is your input string,
Although I honestly don't know why you'd want to do your input validation with php. If you just use javascript, you can give the user a chance to correct the input before the form submits.
除了使用explode() 或substr_count() 的所有这些不错的解决方案之外,为什么不简单地使用PHP 的内置函数来计算字符串中的单词数。我知道函数名称对于此目的来说并不是特别直观,但是:
将是我的建议。
请注意,当使用多字节字符集时,这不一定很有效。 类似以下内容:
在这种情况下,在
str_word_count() 上建议使用
手册页Aside from all these nice solutions using explode() or substr_count(), why not simply use PHP's built-in function to count the number of words in a string. I know the function name isn't particularly intuitive for this purpose, but:
would be my suggestion.
Note, this isn't necessarily quite as effective when using multibyte character sets. In that case, something like:
is suggested on the
str_word_count()
manual page您必须执行两次,一次在客户端使用 JavaScript,然后在服务器端使用 PHP。
You will have to do it twice, once using JavaScript at the client-side and then using PHP at the server-side.
在PHP中,使用split函数将其按空格分割。这样你就会得到一个数组中的单词。然后检查数组的长度。
我没有测试这个。希望这有效。我的机器上现在没有设置PHP环境。
In PHP, use split function to split it by space.So you will get the words in an array. Then check the length of the array.
I didn't test this.Hope this works. I don't have a PHP environment set up on my machine now.
你可以数一下空格的数量...
You could count the number of spaces...
我想你想先用Javascript来做这件事,只允许用户插入5个单词(然后用PHP验证它以避免恶意)
在JS中,你需要在输入字符时计算字符数并保留单词数您编写(通过增加每个空格
的计数器)看一下以下代码: http://javascript.internet.com/forms/limit-characters-and-words-entered.html
i think you want to do it first with Javascript to only allow the user to insert 5 words (and after validate it with PHP to avoid bad intentions)
In JS you need to count the chars as you type them and keep the count of the words you write ( by incrementing the counter each space)
Take a look of this code: http://javascript.internet.com/forms/limit-characters-and-words-entered.html