2011-02-19 107 views
2

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

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

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

回答

3

如果您对允许的字符没有严格的要求,Dalen的建议将运行得更快。但是,自从你提到角色需求以来,这是一个正则表达式解决方案

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

而你只需要在Dalen的回答之后删除你想要的数组。

+0

这是正确的答案 – Dalen 2011-02-19 00:31:19

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); 

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