如何在字符串行中输出重复的字母?

时间:2017-12-21 12:49:04

标签: php string split output

我有像$text = '1234567812349101';这样的字符串我希望能够输出重复的字母以及它们重复的次数。例如,预期结果应为This string 1234 is repeated. Repeated 1 times.

我试过了:

$text = '1234567812349101';

$disp = str_split($text, 4);

foreach ($disp as $char) {

    if (preg_match('/(.{4,})\\1{2,}/', $char)) {
        echo "This string $char is repeated. Repeated times.";
    }
}  

但是没有输出。

我该怎么做?

2 个答案:

答案 0 :(得分:3)

尝试使用array_count_values

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, charset));

String line;
StringBuilder stringBuilder = new StringBuilder();

while((line = bufferedReader.readLine()) != null) {
    stringBuilder.append(line);
}

输出:

$text = '1234567812349101';

$disp = str_split($text, 4);

$dupes = array_filter(array_count_values($disp), function ($el) {
    return ($el > 1);
});

foreach ($dupes as $dupe => $times) {
    echo "This string $dupe is repeated. Repeated " . ($times - 1) . " times.\n";
}

eval.in demo

答案 1 :(得分:0)

   $text = '1234567812349101';

   $disp = str_split($text, 4);
   $count = 0;
   foreach($disp as $char){

       if(strcmp("1234",$char)){
           $count++;
       }
   }  
   $cnt = $count-1;
   if($cnt > 1){
    echo "1234 String is repeated. Repeated ".$cnt."times";
   }

我希望这会帮助你:)