A string contains some words separate开发者_开发技巧d by comma or space. Using PHP, I want to select first three words which have have minimum 4 characters(a-Z, 0-9, -, _, #). For example
$words = aa, one, ab%c, four, five six#
How to select 'four', 'five', six# ? (probably with for each?)
Dalen's suggestion would run much faster if you have no strict requirements for characters allowed. But here is a regex solution since you mention character requirements.
$words = 'aa, one, ab%c, four, five six#';
preg_match_all('/([a-z0-9_#-]{4,})/i', $words, $matches);
print_r($matches);
And you'll just have to cut out what you want from the array after like in Dalen's answer.
//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);
this won't check for the characters, just for the length of the word. you'll need to edit the condition with a regexp
精彩评论