开发者

Restrict text input to only allow five (5) words in PHP

I want to know how I can al开发者_如何学Golow 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.


You can try it like this:

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

should work :-)


If you do;

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

And limit it to 4


If $input is your input string,

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

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.


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:

$wordCount = str_word_count($string);

would be my suggestion.

Note, this isn't necessarily quite as effective when using multibyte character sets. In that case, something like:

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);
} 

is suggested on the str_word_count() manual page


You will have to do it twice, once using JavaScript at the client-side and then using PHP at the server-side.


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.

$mytextboxcontent=$_GET["txtContent"];

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

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

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...

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜