拆分一个字符串,然后按长度将每个单词放入不同的组中


Split a string then put each word into different group by the length

所以我试图根据空间标记整个字符串,然后根据这些标记的长度将这些标记放入不同的组中。我知道如何按空格拆分字符串,但我坚持根据长度将它们放入不同的组。例如,我有一个字符串

你好世界,这是一个考验

因此,在按空格拆分该字符串后,我想检查每个标记的长度,然后将它们放入不同的组中,例如

第1组:a

组 2:是

第3组:测试,这个

第4组:你好,世界

这是我到目前为止的代码:

$strLength = count($string);
$stringSpl = explode(" ", $string);
    if ($strLength <=  2) { //Here I try to check if the length is less than or equal 2 then place it into group 1
        echo "Group 1: ";
        foreach ($stringSpl as $key) {
            echo $key . "<br/>";
        }
    }

任何帮助都会很棒!谢谢!

你快到了,而不是试图计算计数,使用每个字符串/单词中字母的实际计数,使用 strlen()

$words = explode(" ", $s);
$a = array();
foreach($words as $word){
    $a["Group " . strlen($word)][] = $word;
}
print_r(array_reverse($a));

示例/演示

您可以

简单地使用str_word_count函数以及简单的foreachstrlen,例如

$str = "Hello world, this is a test";
$str_arr = str_word_count($str,1);
$result = array();
foreach($str_arr as $v){
    $result["Group ".strlen($v)][] = $v;
}
print_r($result);

演示

这个怎么样?上面的答案已经足够好了,但这很容易

<?
    $string = "Hello world, this is a test";
    $strings = array();
    $stringSpl = explode(" ", $string);
    foreach ($stringSpl as $key) {
        $strings[strlen($key)][] = $key;
    }
    $idx = 1;
    foreach ($strings as $array) {
        echo "group ".($idx++).": ";
        foreach ($array as $key) {
            echo $key." ";
        }
        echo "<br>";
    }
?>

试试这个

$str = "Hello world, this is a test";
$str_arr = str_word_count($str,1);
$result = array();
$i=1;

foreach($str_arr as $v){
$result["Group ".strlen($v)][] = $v;
}
$n=count($result);
echo "<br/>";
$result_array=array_reverse($result);
foreach($result_array as $key=>$value)
{$gorup_value="";
echo $key.' ' ;
$count=count($value);
$i=1;
foreach($value as $key1=>$value1)
{
        $gorup_value .= $value1.',' ;
}
echo    rtrim( $gorup_value , ',');
echo "<br/>";
}

现在编辑然后回答 使用这个