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 :)
Related
Is it possible to take a very long string and split it by sentence into 5000 char (or smaller) array items?
Here's what I have so far:
<?php
$text = 'VERY LONG STRING';
foreach(explode('. ', $text) as $chunk) {
$accepted[] = $chunk;
}
?>
This just splits the string into an array containing single sentence items. I need to group items into sub arrays, each containing a list of items which, when added together, contain no more than 5000 characters.
I tried this:
<?php
$text = 'VERY LONG STRING';
foreach(explode('. ', $text) as $chunk) {
$key = strlen(implode('. ', $accepted).'. '.$chunk) / 5000;
$accepted[$key][] = $chunk;
}
?>
You can probably see what I tried to do here, but it didn't work.
UPDATE:
This did the trick:
<?php
foreach(explode('. ', $text) as $chunk) {
$chunkLen = strlen(implode('. ', $result).'. '.$chunk.'.');
if ($len + $chunkLen > 5000) {
$result[] = $partial;
$partial = [];
$len = 0;
}
$len += $chunkLen;
$partial[] = $chunk;
}
if($partial) $result[] = $partial;
?>
Thank you to everyone who responded, your support means a lot.
You could do something like this:
$text = 'VERY LONG STRING';
$result = [];
$partial = [];
$len = 0;
foreach(explode(' ', $text) as $chunk) {
$chunkLen = strlen($chunk);
if ($len + $chunkLen > 5000) {
$result[] = $partial;
$partial = [];
$len = 0;
}
$len += $chunkLen;
$partial[] = $chunk;
}
if ($partial) {
$result[] = $partial;
}
You can test it more easily if you do it with a lower max length
If I don't misunderstand your question then you need something like this,
<?php
$text = 'VERY LONG STRING';
$s = chunk_split($text, 3, '|'); // put 5000 instead of 3
$s = substr($s, 0, -1);
$accepted = explode('|', $s);
print_r($accepted);
?>
OR
<?php
$text = 'VERY LONG STRING';
$accepted = str_split($text, 3);
print_r($accepted);
?>
DEMO: https://3v4l.org/H9DAl
DEMO: https://3v4l.org/PN7Aj
I want to print * in middle element of odd element of array. here is my code I'm not getting what is the condition I'm write on inner loop? if character length is 7 then how i print * on 4 number character.?
$strings = array("abcdef","abcde","qwert","abcdef","bat");
for ($i=0; $i <count($strings) ; $i++) {
$len = strlen($strings[$i]);
if($len % 2 == 0)
{
echo "Chacater's are even<br>";
}
else{
$string = $strings[$i];
for($j=0; $j<1; $j++)
{
$string[$j] = "*";
}
echo $string."<br>";
}
}
According to my understanding you need to replace the middle char of an odd length element in the array with '*'. This code will give you the desired results.
$strings = array("abcdef","abcde","qwert","abcdef");
$count = count($strings);
for ($i=0; $i<$count; $i++) {
$len = strlen($strings[$i]);
if($len % 2 == 0){
echo "Chacater's are even \n";
}else{
$string = $strings[$i];
// find the center index
$center = floor($len/2);
// replace the center char with *
$string = substr_replace($string, '*', $center,1);
echo $string."\n";
}
}
Out put :
Chacater's are even
ab*de
qw*rt
Chacater's are even
So you want to do like this
<?php
$strings = array("abcdef","abcde","qwert","abcdef");
foreach($strings as $key=> $value){
$strlen = strlen($value);
if($strlen%2 == 0){
echo "\n".$value." :even length";
}else {
if($strlen > 1){
$value[intVal($strlen/2)]="*";
}
echo "\n".$value." :odd length";
}
}
?>
Demo : https://eval.in/850350
http://sandbox.onlinephpfunctions.com/code/1270a1e27b1148e4381ac7882a747ba592b328dc
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>';
}
I've got the problem, that I want to cut-off a long string after the fourth line-break and have it continue with "..."
<?php
$teststring = "asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n";
?>
should become:
<?php
$teststring = "asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa...";
?>
I know how to break the string after the first \n but I don't know how to do it after the fourth.
I hope you can help me.
you can explode the string and then take all the parts you need
$newStr = ""; // initialise the string
$arr = explode("\n", $teststring);
if(count($arr) > 4) { // you've got more than 4 line breaks
$arr = array_splice($arr, 0, 4); // reduce the lines to four
foreach($arr as $line) { $newStr .= $line; } // store them all in a string
$newStr .= "...";
} else {
$newStr = $teststring; // there was less or equal to four rows so to us it'all ok
}
echo preg_replace ('~((.*?\x0A){4}).*~s', '\\1...', $teststring);
Something like this ?
$teststring = "asddsadsadsadsaa
asddsadsadsadsaa
asddsadsadsadsaa
asddsadsadsadsaa
asddsadsadsadsaa
asddsadsadsadsaa";
$e = explode("\n", $teststring);
if (count($e) > 4)
{
$finalstring = "";
for ($i = 0; $i < 4; $i++)
{
$finalstring.= $e[$i];
}
}
else
{
$finalstring = $teststring;
}
echo "<pre>$finalstring</pre>";
I have a string like this:
$string = "1,4|2,64|3,0|4,18|";
Which is the easiest way to access a number after a comma?
For example, if I have:
$whichOne = 2;
If whichOne is equal to 2, then I want to put 64 in a string, and add a number to it, and then put it back again where it belongs (next to 2,)
Hope you understand!
genesis'es answer with modification
$search_for = 2;
$pairs = explode("|", $string);
foreach ($pairs as $index=>$pair)
{
$numbers = explode(',',$pair);
if ($numbers[0] == $search_for){
//do whatever you want here
//for example:
$numbers[1] += 100; // 100 + 64 = 164
$pairs[index] = implode(',',$numbers); //push them back
break;
}
}
$new_string = implode('|',$pairs);
$numbers = explode("|", $string);
foreach ($numbers as $number)
{
$int[] = intval($number);
}
print_r($int);
$string = "1,4|2,64|3,0|4,18|";
$coordinates = explode('|', $string);
foreach ($coordinates as $v) {
if ($v) {
$ex = explode(',', $v);
$values[$ex[0]] = $ex[1];
}
}
To find the value of say, 2, you can use $whichOne = $values[2];, which is 64
I think it is much better to use the foreach like everyone else has suggested, but you could do it like the below:
$string = "1,4|2,64|3,0|4,18|";
$whichOne = "2";
echo "Starting String: $string <br>";
$pos = strpos($string, $whichOne);
//Accomodates for the number 2 and the comma
$valuepos = substr($string, $pos + 2);
$tempstring = explode("|", $valuepos);
$value = $tempstring[0]; //This will ow be 64
$newValue = $value + 18;
//Ensures you only replace the index of 2, not any other values of 64
$replaceValue = "|".$whichOne.",".$value;
$newValue = "|".$whichOne.",".$newValue;
$string = str_replace($replaceValue, $newValue, $string);
echo "Ending String: $string";
This results in:
Starting String: 1,4|2,64|3,0|4,18|
Ending String: 1,4|2,82|3,0|4,18|
You could run into issues if there is more than one index of 2... this will only work with the first instance of 2.
Hope this helps!
I know this question is already answered, but I did one-line solution (and maybe it's faster, too):
$string = "1,4|2,64|3,0|4,18|";
$whichOne = 2;
$increment = 100;
echo preg_replace("/({$whichOne},)(\d+)/e", "'\\1'.(\\2+$increment)", $string);
Example run in a console:
noice-macbook:~/temp% php 6642400.php
1,4|2,164|3,0|4,18|
See http://us.php.net/manual/en/function.preg-replace.php