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

问题描述 投票:0回答:2

我有像$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.";
    }
}  

但是没有输出。

我怎样才能做到这一点?

php string split output
2个回答
3
投票

尝试使用array_count_values

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

输出:

This string 1234 is repeated. Repeated 1 times.

eval.in demo


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

我希望这会帮助你:)

© www.soinside.com 2019 - 2024. All rights reserved.