选择用PHP用逗号分隔的单词

时间:2011-02-19 00:18:41

标签: php

字符串包含由逗号或空格分隔的一些单词。使用PHP,我想选择前三个最少有4个字符的单词(a-Z,0-9, - ,_,#)。 例如

$words = aa, one, ab%c, four, five six#

如何选择'四','五',六#? (可能与每个?)

2 个答案:

答案 0 :(得分:3)

如果对所允许的字符没有严格的要求,那么Dalen的建议会更快。但是,这是一个正则表达式解决方案,因为你提到了字符要求。

$words = 'aa, one, ab%c, four, five six#';
preg_match_all('/([a-z0-9_#-]{4,})/i', $words, $matches);
print_r($matches);

在Dalen的回答中,你只需要从阵列中删除你想要的东西。

答案 1 :(得分:0)

    //turn string to an array separating words with comma    
    $words = explode(',',$words);
    $selected = array();
    foreach($words AS $word)
    {
       //if the word has at least 4 chars put it into selected array
       if(strlen($word) > 3)
          array_push($selected,$word);
    }

    //get the first 3 words of the selected ones
    $selected = array_slice($selected, 0, 3);

这不会检查字符,只是单词的长度。 你需要用正则表达式编辑条件

相关问题