Jump to content

Checking for word length...


phpnoobie9

Recommended Posts

Is this correct...it seems like I just keep getting my else statement when I insert in words into a form.

$longtext should check for words that are longer that 20 characters without any space from the description which is the textarea of the form.

 

 

$description is the textarea name on the form.

$longtext = preg_match('/^\S{20,}$/', $description);
if($description != $longtext) {
if word is not longer than 20 characters do this
else {
if a word has more than 20 characters without any blank space do this
}

Link to comment
https://forums.phpfreaks.com/topic/98412-checking-for-word-length/
Share on other sites

i'd just use strlen()

 

So if I use strlen($description) won't that count every character in $description including space? My goal is to not let the form submit if a there was a word found that has more than 20 characters without a space.

 

i'd just use strlen()

 

and use str_replace() for the spaces.

 

EDIT: beat me to it :P

 

I don't want to replace the word.. I want to echo the else which will say something along the lines of error.

you're not replacing anything except removing the spaces before measuring what's left over.

 

$description = "this is a bit of text";

if(strlen(str_replace(" ","",$description)) <= 20) {
   //if word is not longer than 20 characters do this
else {
   //if a word has more than 20 characters without any blank space do this
}

echo $description;

 

output:

this is a bit of text

 

you're not replacing anything except removing the spaces before measuring what's left over.

 

$description = "this is a bit of text";

if(strlen(str_replace(" ","",$description)) <= 20) {
   //if word is not longer than 20 characters do this
else {
   //if a word has more than 20 characters without any blank space do this
}

echo $description;

 

output:

this is a bit of text

 

 

So " " is equal to space what about ""? Isn't this telling space to replace $description? then...if $description is <= 20 do if..

 

Just need a little explaining so I'll understand the code.

Thanks.

If I understand the problem correctly (you want to find, in a string, if theres at least one word longer than 20 characters),I think your original regex would work if you took out those anchors (the ^ and the $).

 

<?php
$desc = <<<EOF

This is a test sentence with
a supercalafragalisticexpialedocius
word

EOF;

if (preg_match("/\S{20,}/",$desc)) {
    echo "match";
} else {
    echo "no words longer than 20 chars";
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.