Determine repeat characters in a php string - php

I have found many examples of how to find repeat characters in a string. I believe my requirement is unique.
I have string
$string=aabbbccddd;
I need to determine which character was repeated the most.
So for the above example it would say
The character repeated the most is "B".
However in the example above both B and D are repeated 3 times.
Would need to spot that. B AND D are both repeated 3 times.
This is what I have so far. FAR from what I need but starting point
<?php
$string = "aabbbccddd";
$array=array($array);
foreach (count_chars($string, 1) as $i => $val) {
$count=chr($i);
$array[]= $val.",".$count;
}
print_r($array);
?>
Anyone have any thing that could help me?

Based on georg's great point, I would use a regex. This will handle split duplicates like ddaaddd with array keys dd=>2 and ddd=>3 but will only show one entry for dd when given ddaadd. To represent both would require a more complex array:
$string = "ddaabbbccddda";
preg_match_all('/(.)\1+/', $string, $matches);
$result = array_combine($matches[0], array_map('strlen', $matches[0]));
arsort($result);
If you only need a count of ALL occurrences try:
$result = array_count_values(str_split($string));
arsort($result);
Legacy Answers:
If you don't have split duplicates:
$string = 'aabbbccddd';
$letters = str_split($string);
$result = array_fill_keys($letters, 1);
$previous = '';
foreach($letters as $letter) {
if($letter == $previous) {
$result[$letter]++;
}
$previous = $letter;
}
arsort($result);
print_r($result);
Or for a regex approach:
preg_match_all('/(.)\1+/', $string, $matches);
$result = array_combine($matches[1], array_map('strlen', $matches[0]));
arsort($result);

Here's exactly what your looking for :
<?php
function printCharMostRepeated($str)
{
if (!empty($str))
{
$max = 0;
foreach (count_chars($str, 1) as $key => $val)
if ($max < $val) {
$max = $val;
$i = 0;
unset($letter);
$letter[$i++] = chr($key);
} else if ($max == $val)
$letter[$i++] = chr($key);
if (count($letter) === 1)
echo 'The character the most repeated is "'.$letter[0].'"';
else if (count($letter) > 1) {
echo 'The characters the most repeated are : ';
$count = count($letter);
foreach ($letter as $key => $value) {
echo '"'.$value.'"';
echo ($key === $count - 1) ? '.': ', ';
}
}
} else
echo 'value passed to '.__FUNCTION__.' can\'t be empty';
}
$str = 'ddaabbccccsdfefffffqqqqqqdddaaa';
printCharMostRepeated($str);

use count-chars()
http://php.net/manual/en/function.count-chars.php
and then asort()
http://php.net/manual/en/function.asort.php

<?php
$word = "abcdefghbi";
for($i=0; $i<strlen($word);$i++){
for($k=0;$k<strlen($word);$k++){
if($word[$i] == $word[$k] && $i != $k){
echo $word[$k]." is duplicate";
exit;
}
}
}
echo "no match found";
?>

$data = "aabbbcccdddz";
$array = str_split($data);
$v = array_count_values($array);
foreach($v as $k => $val){
echo $k.' = '.$val.'<br>';
}

Related

How do I output a duplicate letter in a string line?

I have string like $text = '1234567812349101'; I want to be able to output the repeated letters and how many times they're repeated. For example the expected result should be This string 1234 is repeated. Repeated 1 times.
I've tried:
$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.";
}
}
But there's no output.
How can I do this?
Try using 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";
}
Output:
This string 1234 is repeated. Repeated 1 times.
eval.in demo
$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";
}
I hope This will help you out :)

fill a series of numbers seperated by dash or comma

I need to fill series of numbers where dash or comma is in use.
I'm using this code that works fine but when numbers starts with zero it's not working (the leading zero drop)
$str = str_replace(' ', '', '11-17,19,041244-041250);
$arr = explode(',', $str);
foreach ($arr as $elem) {
$values = explode('-',$elem);
if (count($values) != 1) {
for($i = $values[0]; $i <= $values[1]; $i++) {
$newArr[]=$i;
}
} else {
$newArr[] = $elem;
}
print_r($newArr);
}
Any help will be appreciated
Try this. Taken from here: Incrementing numbers starting from 0000 in php
<?php
$str = str_replace(' ', '', '11-17,19,041244-041250');
$arr = explode(',', $str);
foreach ($arr as $elem) {
$values = explode('-',$elem);
if (count($values) != 1) {
for($i = $values[0]; $i <= $values[1]; $i++) {
//$newArr[]=$values[0]++;
$newArr[] = str_pad($i + 1, strlen($values[0]), 0, STR_PAD_LEFT);
}
} else {
$newArr[] = $elem;
}
print_r($newArr);
}
This line:
for($i=$values[0];$i<=$values[1];$i++) $newArr[]=$i;
Is the reason this is happening. What you are doing wrong is feeding the initial loop value as a string. You can cast it to an integer and it should fix your problem.
i.e:
for($i=(int)$values[0];$i<=(int)$values[1];$i++) $newArr[]=$i;
Another approach you could consider would be:
$newArr = array_merge($newArr, range((int)$values[0],(int)$values[1]));
Just make sure to initiate $newArr = []; prior to using that method.
Look into: http://php.net/manual/en/function.range.php
<?php
$str = str_replace(' ', '', '11-17,19,041244-041250');
$arr = explode(',', $str);
foreach ($arr as $elem) {
$values = explode('-',$elem);
if (count($values) != 1) {
$newArr[] = $values[0];
for($i = $values[0]; $i < $values[1]; $i++) {
$newArr[] = str_pad($i + 1, strlen($values[0]), 0, STR_PAD_LEFT);
}
}else{
$newArr[] = $elem;
}
}
print_r($newArr);
}

count repeated occurrence of 0 & 1 in a string

Return false if the repeated occurrence of 0's or 1's in the string is greater than number($k).
I have written a function which works, but I need to optimize it:
<?php
function satisfied($str, $k){
$stream = $last = $str[0];
for($i = 1; $i <= strlen($str)-1; $i++){
if($str[$i] != $last) $last = $stream = $str[$i];
else $stream .= $str[$i];
if(strlen($stream) > $k) return false;
}
return true;
}
Example:
satisfied("0111", 2) - False
satisfied("0111", 3) - True
satisfied("00111000111", 3) - True
satisfied("00111000111", 4) - True
I wanted to know if I can do this with help of preg_match?
something like:
preg_match('/(0+|1+){'.$k.'}/', "0111");, this is not even close to what i want to achieve.
I want to avoid for loops to optimize the code. Will the preg_match be faster than the function above ? And obviously, you can also suggest me tweaks to my existing function.
Can someone help me out.
You can do it with strpos:
function satisfied($str, $k) {
return strpos($str, str_repeat('0', $k+1)) === false
&& strpos($str, str_repeat('1', $k+1)) === false;
}
or you can use preg_match with a simple alternation:
function satisfied($str, $k) {
$k++;
$pattern = '~0{' . $k . '}|1{' . $k . '}~';
return !preg_match($pattern, $str);
}
Note that preg_match returns an integer (or false if a problem occurs), but since there is a negation operator, the returned value is casted to a boolean.
You can take the input as character array and Here's exactly what your looking for :
<?php
function printCharMostRepeated($str)
{
if (!empty($str))
{
$max = 0;
foreach (count_chars($str, 1) as $key => $val)
if ($max < $val) {
$max = $val;
$i = 0;
unset($letter);
$letter[$i++] = chr($key);
} else if ($max == $val)
$letter[$i++] = chr($key);
if (count($letter) === 1)
echo 'The character the most repeated is "'.$letter[0].'"';
else if (count($letter) > 1) {
echo 'The characters the most repeated are : ';
$count = count($letter);
foreach ($letter as $key => $value) {
echo '"'.$value.'"';
echo ($key === $count - 1) ? '.': ', ';
}
}
} else
echo 'value passed to '.__FUNCTION__.' can\'t be empty';
}
$str = 'ddaabbccccsdfefffffqqqqqqdddaaa';
printCharMostRepeated($str);

How should merge 2 element of array in PHP?

I want to merge 2 element in array in PHP how can i do that. Please any on tell me.
$arr = array('Hello','World!','Beautiful','Day!'); // these is my input
//i want output like
array('Hello World!','Beautiful Day!');
The generic solution would be something like this:
$result = array_map(function($pair) {
return join(' ', $pair);
}, array_chunk($arr, 2));
It joins together words in pairs, so 1st and 2nd, 3rd and 4th, etc.
Specific to that case, it'd be very simple:
$result = array($arr[0].' '.$arr[1], $arr[2].' '.$arr[3]);
A more general approach would be
$result = array();
for ($i = 0; $i < count($arr); $i += 2) {
if (isset($arr[$i+1])) {
$result[] = $arr[$i] . ' ' . $arr[$i+1];
}
else {
$result[] = $arr[$i];
}
}
In case your array is not fixed to 4 elements
$arr = array();
$i = 0;
foreach($array as $v){
if (($i++) % 2==0)
$arr[]=$v.' ';
else {
$arr[count($arr)-1].=$v;
}
}
Live: http://ideone.com/VUixMS
Presuming you dont know the total number of elements, but do know they will always an even number (else you cant join the last element), you can simply iterate $arr in steps of 2:
$count = count($arr);
$out=[];
for($i=0; $i<$count; $i+=2;){
$out[] = $arr[$i] . ' ' .$arr[$i+1];
}
var_dump($out);
Here it is:
$arr = array('Hello', 'World!', 'Beautiful', 'Day!');
$result = array();
foreach ($arr as $key => $value) {
if (($key % 2 == 0) && (isset($arr[$key + 1]))) {
$result[] = $value . " " . $arr[$key + 1];
}
}
print_r($result);
A easy solution would be:
$new_arr=array($arr[0]." ".$arr[1], $arr[2]." ".$arr[3]);

Return every other character from string in PHP

Assume I have a string variable:
$str = "abcdefghijklmn";
What is the best way in PHP to write a function to start at the end of the string, and return every other character? The output from the example should be:
nljhfdb
Here is what I have so far:
$str = "abcdefghijklmn";
$pieces = str_split(strrev($str), 1);
$return = null;
for($i = 0; $i < sizeof($pieces); $i++) {
if($i % 2 === 0) {
$return .= $pieces[$i];
}
}
echo $return;
Just try with:
$input = 'abcdefghijklmn';
$output = '';
for ($i = strlen($input) - 1; $i >= 0; $i -= 2) {
$output .= $input[$i];
}
Output:
string 'nljhfdb' (length=7)
You need to split the string using str_split to store it in an array. Now loop through the array and compare the keys to do a modulo operation.
<?php
$str = "abcdefghijklmn";
$nstr="";
foreach(str_split(strrev($str)) as $k=>$v)
{
if($k%2==0){
$nstr.= $v;
}
}
echo $nstr; //"prints" nljhfdb
I'd go for the same as Shankar did, though this is another approach for the loop.
<?php
$str = "abcdefghijklmn";
for($i=0;$i<strlen($str);$i++){
$res .= (($i-1) % 2 == 0 ? $str[$i] : "");
}
print(strrev($res)); // Result: nljhfdb
?>
reverse the string then do something like
foreach($array as $key => $value)
{
if($key%2 != 0) //The key is uneven, skip
continue;
//do your stuff
}
loop forward, append backward
<?php
$res = '';
$str = "abcdefghijklmn";
for ($i = 0; $i < strlen($str); $i++) {
if(($i - 1) % 2 == 0)
$res = $str[$i] . $res;
}
echo $res;
?>
preg_replace('/(.)./', '$1', strrev($str));
Where preg_replace replaces every two characters of the reversed string with the first of the two.
How about something like this:
$str = str_split("abcdefghijklmn");
echo join("",
array_reverse(
array_filter($str, function($var) {
global $str;
return(array_search($var,$str) & 1);
}
)
)
);

Categories