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

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.

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

Related

Break up long words in a UTF-8 text, with PHP

Horrible title, I know.
I want to have some kind of wordwrap, but obviously can not use wordwrap() as it messes up UTF-8.. not to mention markup.
My issue is that I want to get rid of stuff like this "eeeeeeeeeeeeeeeeeeeeeeeeeeee" .. but then longer of course. Some jokesters find it funny to put that stuff on my site.
So when I have a string like this "Hello how areeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee you doing?" I want to break up the 'areeee'-thing with the zero width space (​) character.
Strings aren't always the same letter, and strings are always inside larger strings.. so str_len, substr, wordwrap all don't really fit the description.
Who can help me out?
Said that this is not a PHP solution, if your problem is the view of your script, why don't you use the simple CSS3 rule called word-wrap?
Let your container is a div with id="example", you can write:
#example
{
word-wrap: break-word;
}
Do this in 3 steps
do a split on the string and whitespace
do a str_len/trim on each word in the string
concat the string back together
The downside to this would be that words longer than 10 chars would be broken as well. So I would suggest adding some stuff in here to see if it is the same letter in a row over and over.
EXAMPLE
$string = "Hello how areeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee you doing?";
$strArr = explode(" ",$string);
foreach($strArr as $word) {
if(strlen($word) > 10) {
$word = substr($word,0,10);
}
$wordArr[] = $word;
}
$newString = implode(" ",$wordArr);
print $newString; // Prints "Hello how areeeeeeee you doing?"

PHP Remove Value of String with Variable Numbers

Basically from a database I am getting data that is formatted like this nameofproject101 Now this could continue to increase so eventually it could be nameofproject1001 my question is how can I trim off the number and just get the name of the project. I thought about using substr but since I dont know the length always I cant really do that. Since the numbers differ I dont think I can use str_replace is there any way to accomplish this?
It sounds like something is way off about your database scheme. You should probably try to do refactor/normalize your scheme.
But in the meantime, you can use rtrim() to trim all numbers off of the right side.
$val = rtrim($val, '0123456789');
Examples
Input Output
nameofproject1001 nameofproject
nameofproject nameofproject
n4me0fproj3ct1001 n4me0fproj3ct
for string like, project12V123, It is better to do this
$text = `project12V123`;
$text = preg_replace('/([\w]+)([^0-9])([0-9])+$/', '$1$2', $text);
Will return:
Project12V
or use rtrim:
$text = rtrim($text,'0123456789');
You should definitely use regular expressions:
$fullname = "nameofproject101";
preg_match("/([a-z]+)([0-9]+)/i", $fullname, $matches);
$name = $matches[1];
$number = $matches[2];
echo "'$fullname' is '$name' followed by '$number'";
preg_replace('/[^a-z]/i', '', $string);

If a variable only contains one word

I would like to know how I could find out in PHP if a variable only contains 1 word. It should be able to recognise: "foo" "1326" ";394aa", etc.
It would be something like this:
$txt = "oneword";
if($txt == 1 word){ do.this; }else{ do.that; }
Thanks.
I'm assuming a word is defined as any string delimited by one space symbol
$txt = "multiple words";
if(strpos(trim($txt), ' ') !== false)
{
// multiple words
}
else
{
// one word
}
What defines one word? Are spaces allowed (perhaps for names)? Are hyphens allowed? Punctuation? Your question is not very clearly defined.
Going under the assumption that you just want to determine whether or not your value contains spaces, try using regular expressions:
http://php.net/manual/en/function.preg-match.php
<?php
$txt = "oneword";
if (preg_match("/ /", $txt)) {
echo "Multiple words.";
} else {
echo "One word.";
}
?>
Edit
The benefit to using regular expressions is that if you can become proficient in using them, they will solve a lot of your problems and make changing requirements in the future a lot easier. I would strongly recommend using regular expressions over a simple check for the position of a space, both for the complexity of the problem today (as again, perhaps spaces aren't the only way to delimit words in your requirements), as well as for the flexibility of changing requirements in the future.
Utilize the strpos function included within PHP.
Returns the position as an integer. If needle is not found, strpos()
will return boolean FALSE.
Besides strpos, an alternative would be explode and count:
$txt = trim("oneword secondword");
$words = explode( " ", $txt); // $words[0] = "oneword", $words[1] = "secondword"
if (count($words) == 1)
do this for one word
else
do that for more than one word assuming at least one word is inputted

How do I allow for user input of words sparated by commas and spaces? PHP

what I am trying to do is allow for users to input keywords sparated by a comma and a space (ex: word, word, word, word). There is no limit on the number of words or anything, I would simply like the format to be respected. Thank you!
Well if you wanted to be exact you would use:
$tags = explode(', ',$input);
A more happy matching without using regex:
$tags = explode(',',$input);
for($i=0;$i<count($tags);$i++) {
$tags[$i] = trim($tags[$i]);
}
And using regular expressions:
$tags = preg_split('/\s*,\s*/',$input,-1,PREG_SPLIT_NO_EMPTY);
you can simply use explode to split a string into part's.
$words = explode(', ',$_POST['words']);
You can reformat user input on server-side and don't force them to worry about format. Just write function to do it for you. Something like
$correct_input = reformatInput($user_input);
Function reformatInput() might be like this one
function reformatInput($inp) {
$inparr = explode(" ", str_replace(",", " ", $inp));
$res = array();
foreach ($inparr as $item) if ($item != '') $res[] = $item;
return join(", ", $res); // join() is alias of implode()
}
This function returns string containing words separated with comma+space or empty string if there are no words in user's input.
Now if you have user input like this one for example
$user_input = " word1,word2, word3,, word4, word5 word6 word7 ,,,";
you can reformat it using that function and output in correct format
$correct_input = reformatInput($user_input);
echo "user input ($correct_input)";
Output based on this example will be
user input (word1, word2, word3, word4, word5, word6, word7)
Generally, that's result what you want in first place.
Note: You can use Ajax to reformat their input, onExit event of input element and store it back (correct format) in that input field, or rewrite this function in JavaScript and do it at client-side, but in that case, you should check it on server side again and it doesn't work if client disables JavaScript in his/hers browser.
You can do it without regular expressions as you can see, easily.
References:
explode()
join(), or its alias implode()
foreach loop

PHP - Sanitise a comma separated string

What would be the most efficient way to clean a user input that is a comma separated string made entirely on numbers - e.g
2,40,23,11,55
I use this function on a lot of my inputs
function clean($input){ $input=mysql_real_escape_string(htmlentities($input,ENT_QUOTES)); return $input; }
And on simple integers I do:
if (!filter_var($_POST['var'], FILTER_VALIDATE_INT)) {echo('error - bla bla'); exit;}
So should I explode it and then check every element of the array with the code above or maybe replace all occurrences of ',' with '' and then check the whole thing is a number? What do you guys think?
if (ctype_digit(str_replace(",", "", $input))) {
//all ok. very strict. input can only contain numbers and commas. not even spaces
} else {
//not ok
}
If it is CSV and if there might be spaces around the digits or commas and maybe even some quotation marks better use a regex to check if it matches
if (!preg_match('/\A\d+(,\d+)*\z/', $input)) die('bad input');
If you want to transform a comma-separated list instead of simply rejecting it if it's not formed correctly, you could do it with array_map() and avoid writing an explicit loop.
$sanitized_input = implode(",", array_map("intval", explode(",", $input)));
I would filter instead of error checking on simple input, though only 'cause I'm lazy, I suppose, and usually in a web context there's way too many cases to handle on what could be coming in that I wouldn't expect: Simple filter below.
<?php
$input = '234kljsalkdfj234a,a, asldkfja 345345sd,f jasld,f234l2342323##$##';
function clean($dirty){ // Essentially allows numbers and commas, just strips everything else.
return preg_replace('/[^0-9,]/', "", (string) $dirty);
}
$clean = clean($input);
echo $clean;
// Result: 234234,,345345,,2342342323
// Note how it doesn't deal with adjacent filtered-to-empty commas, though you could handle those in the explode. *shrugs*
?>
Here's the code and the output on codepad:
http://codepad.org/YfSenm9k

Categories