开发者

PHP: word check for 30 chars

开发者 https://www.devze.com 2023-01-25 11:06 出处:网络
I would like to check that if $_POST[msg] contains a word that are longer than 30 chars(without no spaces) so you wouldnt be able 开发者_开发技巧to write:

I would like to check that if $_POST[msg] contains a word that are longer than 30 chars(without no spaces) so you wouldnt be able 开发者_开发技巧to write:

example1 :

asdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsdsddsasdsdsdsdsd

example2: hello my name is asdoksdosdkokosdkosdkodskodskodksosdkosdkokodsdskosdkosdkodkoskosdkosdkosdkosdsdksdoksd

(notice no spaces).

How can I do that?


You could use preg_match to look for that as follows...

if (preg_match('/\S{31,}/', $_POST['msg']))
{
     //string contains sequence of non-spaces > 30 chars
}

The /S matches any non-space character, and is the inverse of /s which matches any space. See the manual page on PCRE escape sequences


You can use the regex \w{31,} to find for a word that has 31 or more characters:

if(preg_match('/\w{31,}/',$_POST['msg'])) {
        echo 'Found a word >30 char in length';
}

If you want to find group of non-space characters that are 31 or more characters in length, you can use:

if(preg_match('/\S{31,}/',$_POST['msg'])) {
        echo 'Found a group of non-space characters >30 in length';
}


First find the words:

// words are separated by space usually, add more logic here
$words = explode(' ', $_POST['msg']);

foreach($words as $word) {
    if(strlen($word) > 30) { // if the word is bigger than 30
        // do something
    }
}


How about this? Just difference in logic

if (strlen(preg_replace('#\s+#', '', $_POST['msg'])) > 30) {
    //string contain more then 30 length (spaces aren't counted)
}


First split the input into words:

explode(" ", $_POST['msg']);

then get the maximum length string:

max(explode(" ", $_POST['msg']));

and see if that is larger than 30:

strlen(max(explode(" ", $_POST['msg']))) > 30
0

精彩评论

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