Reputation: 3749
The following code splits a string and selects all of the alphanumeric words containing minimum 3 letters. However instead of getting all the words from the string, I want to get only first 3 valid words, but the problem is with the loop. How can I stop the loop as soon as 3 valid words are found from the string.
PS. If there is an alternative approach to the same thing, please suggest. Thanks.
$string = "test test TEST test- -test _test blsdk.bldf,las";
$arr = preg_split('/[,\ \.;]/', $string);
$keywords = array_unique($arr);
foreach ($keywords as $keyword){
if ((preg_match("/^[a-z0-9]/", $keyword) ) && (strlen($keyword) > 3)){
echo $keyword;
echo "<br />";
}
}
Upvotes: 0
Views: 6015
Reputation: 14959
I would use a different approach As you use a regex to check your results maybe it is more clear, and maybe efficients, to use preg_match_all to do your work for you.
<?php
$string = "test le test TEST test- -test _test blsdk.bldf,las";
$arr=array();
preg_match_all('/\b([0-9A-Za-z]{3,})\b/', $string, $arr);
$keywords = array_slice(array_unique($arr[0]),0,3);
echo join('<br/>', $keywords);
In the question you state you want to select words with a minimum length of 3,
but you test their length with > 3
. Change the regular expression accordingly if needed.
Note: made the words unique as in the original test.
Upvotes: 1
Reputation: 24236
I think you need the 'break' keyword, try this (code not tested) -
$string = "test test TEST test- -test _test blsdk.bldf,las";
$arr = preg_split('/[,\ \.;]/', $string);
$keywords = array_unique($arr);
$counter = 0;
foreach ($keywords as $keyword){
if ((preg_match("/^[a-z0-9]/", $keyword) ) && (strlen($keyword) > 3)){
echo $keyword;
echo "<br />";
$counter = $counter + 1;
if ($counter == 3) break;
}
}
Upvotes: 1
Reputation: 7722
add a variable which counts up when a matching keyword is found. when counter reaches maximum then break the foreach
loop
$string = "test test TEST test- -test _test blsdk.bldf,las";
$arr = preg_split('/[,\ \.;]/', $string);
$keywords = array_unique($arr);
$i=0;
foreach ($keywords as $keyword){
if ((preg_match("/^[a-z0-9]/", $keyword) ) && (strlen($keyword) > 3)){
echo $keyword;
echo "<br />";
$i++;
if ($i==3) break;
}
}
Upvotes: 3