将文本输入限制为仅允许PHP中的五(5)个单词

时间:2010-10-20 02:26:02

标签: php input count

我想知道如何使用PHP在文本输入上只允许五(5)个单词。

我知道我可以使用strlen函数进行字符计数,但我想知道如何才能用文字来表达。

8 个答案:

答案 0 :(得分:7)

你可以这样试试:

$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";

应该有效: - )

答案 1 :(得分:2)

如果你这样做;

substr_count($_POST['your text box'], ' ');

并将其限制为4

答案 2 :(得分:1)

如果$ input是您的输入字符串,

$wordArray = explode(' ', $input);
if (count($wordArray) > 5)
  //do something; too many words

虽然老实说我不知道​​你为什么要用php进行输入验证。如果您只是使用javascript,则可以在表单提交之前让用户有机会更正输入。

答案 3 :(得分:1)

除了使用explode()或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()手册页

答案 4 :(得分:0)

你必须做两次,一次在客户端使用JavaScript,然后在服务器端使用PHP。

答案 5 :(得分:0)

您可以计算空格数......

$wordCount = substr_count($input, ' ');

答案 6 :(得分:0)

在PHP中,使用split函数按空格分割。因此,您将获得数组中的单词。然后检查数组的长度。

$mytextboxcontent=$_GET["txtContent"];

$words = explode(" ", $mytextboxcontent);
$numberOfWords=count($words);

 if($numberOfWords>5)
 {
   echo "Only 5 words allowed";
 }
 else
 {
  //do whatever you want....
 }

我没有测试过这个。希望这个有效。我现在没有在我的机器上设置PHP环境。

答案 7 :(得分:0)

我认为您希望首先使用Javascript来允许用户插入5个单词(并在使用PHP验证之后避免出现不良意图)

在JS中,您需要在键入时计算字符数并保留您编写的字数(通过递增每个空格的计数器)

看一下这段代码:http://javascript.internet.com/forms/limit-characters-and-words-entered.html