PHP /正则表达式,用于检查字符串是否包含特定长度的单词

时间:2010-07-17 14:04:24

标签: php regex string

我需要检查收到的字符串是否包含长度超过20个字符的单词。例如输入字符串:

嗨,你好吗?ssssssssssssssskkkkkkk你好吗?

会返回true。

有人可以帮我拿一个regexp来检查这个。我正在使用php。

提前感谢。

3 个答案:

答案 0 :(得分:4)

/\w{20}/

...填充15个字符....

答案 1 :(得分:3)

您可以测试字符串是否包含以下模式的匹配项:

[A-Za-z]{20}

构造[A-Za-z]创建一个匹配ASCII大写和小写字母的字符类。 {20}是有限重复语法。它足以检查是否存在包含20个字母的匹配项,因为如果有一个包含更多字母的单词,则它至少包含20个字母。

参考


PHP代码段

以下是一个示例用法:

$strings = array(
  "hey what the (@#$&*!@^#*&^@!#*^@#*@#*&^@!*#!",
  "now this one is just waaaaaaaaaaaaaaaaaaay too long",
  "12345678901234567890123 that's not a word, is it???",
  "LOLOLOLOLOLOLOLOLOLOLOL that's just unacceptable!",
  "one-two-three-four-five-six-seven-eight-nine-ten",
  "goaaaa...............aaaaaaaaaalll!!!!!!!!!!!!!!",
  "there is absolutely nothing here"
);

foreach ($strings as $str) {
  echo $str."\n".preg_match('/[a-zA-Z]{20}/', $str)."\n";
}

打印(as seen on ideone.com):

hey what the (@#$&*!@^#*&^@!#*^@#*@#*&^@!*#!
0
now this one is just waaaaaaaaaaaaaaaaaaay too long
1
12345678901234567890123 that's not a word, is it???
0
LOLOLOLOLOLOLOLOLOLOLOL that's just unacceptable!
1
one-two-three-four-five-six-seven-eight-nine-ten
0
goaaaa...............aaaaaaaaaalll!!!!!!!!!!!!!!
0
there is absolutely nothing here
0

如模式中所指定的,当有一个至少20个字符长的“单词”(由一系列字母定义)时,preg_match为真。

如果“单词”的定义不合适,那么只需将模式更改为,例如\S{20}。也就是说,20个非空白字符的任何序列;现在除了最后一个字符串之外的所有字符串都匹配(as seen on ideone.com)。

答案 2 :(得分:-1)

我认为strlen功能正是您所寻求的。你可以这样做:

if (strlen($input) > 20) {
    echo "input is more than 20 characters";
}