i have string AABBBCCCDABBAACBB , in this i need to find the most occurrence of Character , how can i find this??
in above string it should return 7 ad B comes 7 times i.e max.
$str = "AABBBCCCABB";
$strArray = count_chars($str,1);
foreach ($strArray as $key=>$value)
{
echo "The character <b>'".chr($key)."'</b> was found $value time(s)<br>";
//$highest=chr($key);
if(isset($highest) && $highest>chr($key))
{
$highest=chr($key);
}
}
echo "<br/><br/>Highest value is ::".$highest;
above code i tried,
i tried but functionality is not perfect , which function of php i should use?
You don't need a loop for this. Use array_search() to find the key of the most repeated value, and use chr() on it:
$str = "AABBBCCCDABBAACBB";
$strArray = count_chars($str,1);
echo chr(array_search(max($strArray), $strArray));
Output:
B
Demo!
$string="AABBBCCCABB";
foreach (str_split($string) as $s){
if (isset($counts[$s])) continue;
$counts[$s]=substr_count($string, $s);
echo "The character <b>'" . $s . "'</b> was found ".$counts[$s]." time(s)<br>";
}
$maxs=array_keys($counts, max($counts));
echo "Highest value is ::'".$maxs[0];
Solution for your code by your way:
$str = "AABBBCCCABB";
$strArray = count_chars($str,1);
$highest = $str[0];
$times = 0;
foreach ($strArray as $key=>$value){
echo "The character <b>'".chr($key)."'</b> was found $value time(s)<br>";
//$highest=chr($key);
if($times < $value)
{
$times = $value;
$highest=chr($key);
}
}
echo "<br/><br/>Highest value is ::".$highest;
But answer of Alma Do is better to use.
You could also use the max() function:
$str = "AABBBCCCABB";
$strArray = count_chars($str,1);
$highest = max($strArray);
foreach ($strArray as $key=>$value) {
echo "The character <b>'" . chr($key) . "'</b> was found $value time(s)<br>";
}
echo "<br/><br/>Highest value is ::" . $highest;
Try this solution, hope this helps you to solve.
$string = "AABBBCCCABB";
$letters = array_count_values(str_split($string));
$val = array_search(max($letters), $letters);
echo $val;
Try this..
echo maxCountChar("AABBBCCCDABBAACBB");
function maxCountChar($string){
foreach (str_split($string) as $s){
$counts[$s]=substr_count($string, $s);
}
$maxs=array_keys($counts, max($counts));
$num = substr_count($string, $maxs[0]);
return "The character <b>$maxs[0]</b> was found <b>$num</b> times";
}
Output
The character B was found 7 times
Related
I want to cut text in array but I have no idea to cut this
I try strstr() but it not true.
I try
$ff='';
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$ff .= $row['fav'] . ",";
}
if( strpos( $ff, "_" )) {
$text = strstr($ff, '_');
echo $text;
}
$ff ='A_0089,A_5677,B_4387,A_B_5566,'
I want output show
0089,5677,4387,B_5566,
Here is one example, using substr() with strpos():
$ff='A_0089,A_5677,B_4387,A_B_5566';
$items = explode(',', $ff);
foreach($items as $item) {
echo substr($item, strpos($item, '_')) . "\n";
}
The above code returns:
_0089
_5677
_4387
_B_5566
You're better off not building a string, but building an array. The way you build the string you have a dangling comma, which you do not want.
$ff = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$ff[] = $row['fav'];
}
foreach($ff as $item) {
echo substr($item, strpos($item, '_')) . "\n";
}
Based on your desire to keep the commas and create a string:
$ff='A_0089,A_5677,B_4387,A_B_5566,';
$items = explode(',', $ff);
foreach($items as $item) {
$new[] = substr($item, strpos($item, '_'));
}
$newFF = implode(',', $new);
echo $newFF;
returns:
_0089,_5677,_4387,_B_5566,
Probably this is what you are looking for
<?php
function test_alter(&$item1)
{
$pattern = '/^[A-Z]{1}[_]{1}/';
$item1 =preg_replace($pattern,"",$item1);
}
$ff="A_0089,A_5677,B_4387,A_B_5566,";
$nff=explode(",",$ff);
array_walk($nff, 'test_alter');
echo implode(",",$nff);
?>
So I am trying to tokenizes the entire string based on the space and then put those tokens into different groups based on length of those tokens. I got how to split a string by space but I am stuck on put them into different group based on the length. For example, I have a string
Hello world, this is a test
So after split that string by space, I want to check the length of each token and then put them into different group like
Group 1: a
Group 2: is
Group 3: test, this
Group 4: hello, world
This is my code so far:
$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/>";
}
}
Any help would be great! Thank you!
You're almost there, instead of trying to figure out the count, use the actual count of letters in each string/word, using strlen():
$words = explode(" ", $s);
$a = array();
foreach($words as $word){
$a["Group " . strlen($word)][] = $word;
}
print_r(array_reverse($a));
Example/Demo
You can simply use str_word_count function along with simple foreach and strlen like as
$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);
Demo
How about this? Above answers are great enough, but this is easy
<?
$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>";
}
?>
Try this
$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/>";
}
Now Edited then Answer Use this
I have a string like
$totalValues ="4565:4,4566:5,4567:6";
Now i want only values after ':' with coma separated ,i.e i want string like $SubValues = "4,5,6"
Thanks
using array_map, implode and explode
$totalValues ="4565:4,4566:5,4567:6";
echo implode(',',array_map(function($val){
$val = explode(':',$val);
return $val[1];
},explode(',',$totalValues)));
try this code it is working
<?php
$str="4565:4,4566:5,4567:6";;
$data =explode(",", $str);
echo '<pre>';
print_r($data);
$newstring="";
foreach ($data as $key => $value) {
preg_match('/:(.*)/',$value,$matches);
$newstring.=$matches[1].",";
}
echo rtrim($newstring,",");
Output
i have updated my code please check it
<?php
$str="4565:4,4566:5,4567:6";
$data1=explode(",", $str);
$newstring1="";
foreach ($data1 as $key1 => $value) {
preg_match('/(.*?):/',$value,$matches);
$newstring1.=$matches[1].",";
}
echo rtrim($newstring1,",");
you might want it this way:
$totalValues ="4565:4,4566:5,4567:6";
$temp = explode(':', $totalValues);
$subValues = $temp[1][0];
$x = count($temp);
for ($i = 2; $i < $x; $i++) {
$subValues .= ',' . $temp[$i][0];
}
echo $subValues;
I want string format with incremental numbers. I've strings starting with alphabets and containing numbers with few leading 0's.
$string = M001; //input
$alf= trim(str_replace(range(0,9),'',$string)); //removes number from string
$number = preg_replace('/[A-Za-z]+/', '', $string);// removes alphabets from the string
$number+=1;
$custom_inv_id = $alf.$number;
Expected result:
input M002 output M003
input A00003 output A00004
Using above code if input is M002, I'm getting output as M3. How I can get M003? Number of 0's is not fixed.
Use PHP preg_match or str_replace and try this code :-
$str='M001';
preg_match('!\d+!', $str, $matches);
$num=(int)$matches[0];
$num++;
echo str_replace((int)$matches[0],'',$str);
echo $num;
Demo
<?php
$tests = ['M0', 'M1', 'M001', 'M9', 'M09', 'M010',
'M2M0', 'M2M1', 'M2M001', 'M2M9', 'M2M09', 'M2M010',
'M2M', 'MM', '9M'];
foreach ($tests as $string) {
if (preg_match('/([\w\W]+)([0-9]+)$/', $string, $matches)) {
$output_string = $matches[1] . ($matches[2] + 1);
echo '<p>' . $string . ' => ' . $output_string . '</p>';
} else {
echo '<p>' . $string . ' (nothing to increment)</p>';
}
}
$a = 'm002';
$pattern = '#(?P<word>[A-Za-z0]+)(?P<digtt>[1-9]+)#';
preg_match($pattern, $a, $matches);
$final = $matches['word'].(string)($matches['digtt']+1);
echo $final;
You can use the sprintf and preg_match functions to get your expected result.
First: Split your string with preg_match to seperated values to work with
Second: Format a new string with sprintf
http://php.net/manual/en/function.sprintf.php
http://php.net/manual/en/function.preg-match.php
function increase($string, $amount = 1) {
$valid = preg_match("#^(.)(0+)?(\d+)$#s", $string, $matches);
if($valid) {
list($match, $char, $zero, $integer) = $matches;
$integer += $amount;
return sprintf("%s%'.0" . (strlen($zero)+1) . "d", $char, $integer);
}
return null;
}
echo increase("M00001"); // M00002
echo increase("A001", 5); // A006
i hope this can help you . i have made some thing dynamic make M% also dynamic
<?php
$vl = "A00004";
$number = substr($vl ,1);
$num= substr_count($vl,0);
$num++;
$number++;
$string = "M%'. 0".$num."d";
echo sprintf($string, $number);
?>
i got this result
M00005
As leading 0 is copied, I would do it like this. It works if the leading chars is also lowercase. It's also a non-regex and non-array way.
$str = "M0099";
$num = ltrim($str, "a..zA..Z0");
$new = str_replace($num, $num + 1, $str);
Output:
echo $new; // string(6) "M00100"
$search=array("<",">","!=","<=",">=")
$value="name >= vivek ";
I want to check if $value contains any of the values of the $search array. I can find out using foreach and the strpos function. Without resorting to using foreach, can I still find the answer? If so, kindly help me to solve this problem.
Explode $value and convert it into array and then use array_intersect() function in php to check if the string does not contain the value of the array.Use the code below
<?php
$search=array("<",">","!=","<=",">=");
$value='name >= vivek ';
$array = explode(" ",$value);
$p = array_intersect($search,$array);
$errors = array_filter($p);
//Check if the string is not empty
if(!empty($errors)){
echo "The string contains an value of array";
}
else
{
echo "The string does not containe the value of an array";
}
?>
Test the code here http://sandbox.onlinephpfunctions.com/code/7e65faf808de77036a83e185050d0895553d8211
Hope this helps you
Yes, but it will require you to re structure your code.
$search = array("<" => 0, ">" => 1,"!=" => 2,"<=" => 3,">=" => 4);
$value = "name => vivek ";
$value = explode(" ", $value);
foreach($value as $val) {
// search the array in O(1) time
if(isset($search[$val])) {
// found a match
}
}
Use array_map() and array_filter()
function cube($n)
{
$value="name => vivek ";
return strpos($value, $n);
//return($n * $n * $n);
}
$a = array("<",">","!=","<=",">=");
$value="name => vivek ";
$b = array_map("cube", $a);
print_r($b);
$b = array_filter($b);
print_r($b);
$search = array("<",">","!=","<=",">=");
$value="name => vivek ";
foreach($value as $searchval) {
if(strpos($value, $searchval) == false)
{
echo "match not found";
}
else
{
echo "match found";
}
}
Here's a solution using array_reduce:
<?PHP
function array_in_string_callback($carry, $item)
{
list($str, $found) = $carry;
echo $str . " - " . $found . " - " . $str . " - " . $item . "<br/>";
$found |= strpos($str, $item);
return array($str, (boolean) $found);
}
function array_in_string($haystack, $needle)
{
$retVal = array_reduce($needle, "array_in_string_callback", array($haystack, false));
return $retVal[1];
}
$search=array("<",">","!=","<=",">=");
$value="name >= vivek ";
var_dump(array_in_string($value, $search));
?>
My first inclination was to solve the problem with array_walk() and a callback, as follows:
<?php
$search=array("<",">","!=","<=",">=");
$value = "name >= vivek ";
function test($item, $key, $str)
{
if( strpos($str, $item) !== FALSE ) {
echo "$item found in \"$str\"\n";
}
}
array_walk($search, 'test', $value);
// output:
> found in "name >= vivek "
>= found in "name >= vivek "
Live demo: http://3v4l.org/6B0WX
While this solves the problem without a foreach loop, it answers the question with a "what" rather than a "yes/no" response. The following code directly answers the question and permits answering the "what" too, as follows:
<?php
function test($x)
{
$value="name >= vivek ";
return strpos($value, $x);
}
$search = array("<",">","!=","<=",">=");
$chars = array_filter( $search, "test" );
$count = count($chars);
echo "Are there any search chars? ", $answer = ($count > 0)? 'Yes, as follows: ' : 'No.';
echo join(" ",$chars);
// output:
Are there any search chars? Yes, as follows: > >=
Live demo: http://3v4l.org/WJQ5c
If the response had been negative, then the output is 'No.' followed by a blank space.
A key difference in this second solution compared to the first, is that in this case there is a return result that can be manipulated. If an element of the array matches a character in the string, then array_filter adds that element to $chars. The new array's element count answers the question and the array itself contains any matches, if one wishes to display them.