Re: Counting number of characters without spaces between them?

From: Date: Fri, 23 Apr 2004 14:36:16 +0000
Subject: Re: Counting number of characters without spaces between them?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-184393@lists.php.net to get a copy of this message
"Richard Davey" <rich@launchcode.co.uk> wrote in message news:576448116.20040423145056@launchcode.co.uk... > Hi all, > > It's a warm sunny day and I'm trying to wrap my head around the > following: > > I want to be able to check to see if, in a string, the user has > entered too many consecutive characters and not enough spaces. For > example they might enter a subject like: > > "hello world!!!!!!!!!!!!!!!!! how arrrrrrrrrrrrrrre you today?????!!" > > Does anyone have a nice technique for checking the following: > > 1) Count the length of the words in the string, i.e. if there are any > words beyond say 20 characters then I need to know what they are so I > can flag up a warning. > > 2) Count the number of punctuation characters vs. alphanumerics - I > don't want the exclamation mark syndrome shown above, so I need to set > a friendly trade-off limit somehow. > > Any thoughts appreciated. > > -- > Best regards, > Richard Davey > http://www.phpcommunity.org/wiki/296.html Hi Richard, to count the words and check its length you could use explode() to split the string into an array by a space (' '): $words = explode(' ', $input); $allowedWordLength = 20; $tooLongWord = false; $checkChar = '!'; $tooManyChars = false; // loop through the array and check each word's length and char occurrence foreach ($words as $word) { if (strlen($word) > $allowedWordLength) $tooLongWord = true; // check the occurrence of a special character in the word if (substr_count($word, $checkChar) > 1) $tooManyChars = true; } // print an error if one of the words is too long if ($tooLongWord) echo 'Error: Your words are too long!'; // print an error if the checked char occurred too often in one of the words if ($tooManyChars) echo 'You had too many ' . $checkCar . ' in your input!'; The above code is not tested but should work. Hope this helps. Regards, Torsten

« previous php.general (#184393) next »