![](/img/trans.png)
[英]count each character for each word in a string and put the word with less than 5 characters in array using php
[英]Split a string then put each word into different group by the length
因此,我嘗試根據空間對整個字符串進行標記化,然后根據這些標記的長度將這些標記放入不同的組中。 我知道如何按空格分割字符串,但是我堅持根據長度將它們分成不同的組。 例如,我有一個字符串
世界,您好,這是一個測試
因此,按空格分割該字符串后,我想檢查每個令牌的長度,然后將它們放入不同的組中,例如
第一組:a
第2組:是
第三組:測試
第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/>";
}
}
任何幫助將是巨大的! 謝謝!
您可以簡單地將str_word_count
函數與簡單的foreach
和strlen
一起使用,如下所示
$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/>";
}
現在編輯然后回答使用此
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.