0

如何在 PHP 中做这样的事情?我喜欢这个论坛唯一的 C# 解决方案如何检查字符串是否包含超过 50 个字符的单词?

例如我有一个字符串:

$string_to_check = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa rrrr fe we we hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhererererereerdfsdfsdfsdfsdfsdfsdfsdfsdfsdfttttfsd hhghhhhhhhhhhhhhhhhhh fd s hoefjsd k
bla bla bla";

而且我想创建一个 if 条件,所以当字符串包含一个长度为 50 个或更多字符的单词时,返回 false;否则返回真;

任何如何解决这个问题的建议表示赞赏。

4

5 回答 5

4

试试这个功能:

function not_long_word($sentence, $length = 50) {
    $words = explode(' ', $string);
    foreach ($words as $key => $value) {
      if (strlen($value) > $length) return false;
    }
    return true;
}

用法:

$text = "word wooooooooooooooooooooooooooooooooooooooooooooooooooooooooooord";
if (not_long_word($text)) {
    echo "there no word longer than 50!";
}
于 2012-09-13T20:30:10.733 回答
1
$str = "a word in-this-string-contains-fifty-or-more-ch ";

if(preg_match('/\S{50,}/',$str)) 
{ 
   echo 'String contains a word of more than 50 characters'; 
} 
else 
{ 
   echo 'String does not contains a word of more than 50 characters'; 
} 
于 2015-12-12T11:07:35.423 回答
0

它应该是这样的:

if(strlen($string_to_check) < 50 )
{
 ...
}
else {
...
}
于 2012-09-13T20:31:26.230 回答
0

首先,将其拆分成单独的单词(假设空格是分隔符),然后找出是否有任何单词超过 50 个字符:

$array = explode(" ",$string);
foreach ($array as $word) { 
  if (strlen($word) > 50) {
    echo "{$word}\n"
  }
}

如果分隔符可能有多个空格/制表符,那么您可以选择正则表达式:

$array = preg_split('[\t\s]+', $string);
于 2012-09-13T20:31:57.347 回答
0

对此进行了测试,效果很好。

check_word_length( $string_to_check );

function check_word_length( $string_to_check ){
    foreach ( explode(' ', $string_to_check )  as $word) {
        if ( strlen($word) > 50 ) return false;
    }
    return true;
}
于 2012-09-13T21:28:28.863 回答