简体   繁体   中英

PHP Get first 3 words from string

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 />";
            }
        }

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

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

只是切断其余部分。

array_splice($arr, 3);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM