I Need PHP Function that can get the most letters from the string
$string = "111010111010001101";
$execute = SomeFunction($string);
echo $execute;
and the ouput will be like this
1
is there a php function like that? Thank you
Here you go
$string = "111010111010001101";
//$string = "abaacabdeeeee";
$array_count = array_count_values(str_split($string));
$res = array_keys($array_count, max($array_count));
print_r($res);
To make it a function, just do this:
function SomeFunction($string){
$array_count = array_count_values(str_split($string));
return array_keys($array_count, max($array_count));
}
print_r(SomeFunction('111010111010001101'));
Output
1 //or e in the commented one I tested
Sandbox
How it works:
Split the string into an array of chars str_split
count the occurrences of the chars array_count_values
get the key with the max number of occurrences array_keys and max
Caveats:
If two values are equal then they will both be returned in the result. For example
$string = 'ababababcd';
Output
Array
(
[0] => a
[1] => b
)
You never mentioned what you want to happen in this case (a tie). For your particular case that may not even be an issue. But I had to mention it for the sake of completeness. If you don't want the return as an array you can do something like this (to return false or the first element):
function SomeFunction($string){
$array_count = array_count_values(str_split($string));
$res = array_keys($array_count, max($array_count));
if(empty($res)) return false;
return array_shift($res);
}
Cheers!
Not effective but simple
max(str_split($string));
Yes, so long as your character set isn't a multibyte one with multibyte characters in the string. See the manual page for count_chars
Related
//array data
{
$results[] = $result;
$SiteID=$result["site_id"];
$pay_sale_id=$result["pay_sale_id"];
$pay_payment_info=$result["pay_payment_info"];
$payNo= substring_index(substring_index('$result["pay_payment_info"]', '$USER=', -1), '~$TAGROLE', 1);
}
The content of pay_payment_info is as follows
#$TAG=6F0000173~$USER=james~$TAGROLE=0
I want to extract only the user info, but i get error:
Fatal error: Call to undefined function substring_index() in line
Considering the user info always begins with ~$USER= and ends with a ~ we can get the result using simple regex:
preg_match('/\~\$USER=(?<user>[^~]+)/', $pay_payment_info, $match);
var_dump($match['user']);
As previous comments said - there is no such function like substring_index in core PHP
This question is possible duplicate of following Php get string between tags
topic
Here is working example with usage of strpos http://php.net/manual/pl/function.strpos.php
and substr http://php.net/manual/pl/function.substr.php
$var = '$TAG=6F0000173~$USER=james~$TAGROLE=0';
$m = substr($var, strpos($var, '~$USER=')+7);
var_dump($m); //returns string(16) "james~$TAGROLE=0"
$m = substr($m, 0, strpos($m, '~$'));
var_dump($m); //returns string(5) "james"
it seems that the problem is you have no substring_index() function or method, yet you attempt to invoke it twice.
I am not sure why you use the ~ as a delimiter but that should be ok, although using a , would have resulted in less work; each of the attributes of your querystring would have been able to be addressed directly then.
what you want to do is use the php version of split() which is explode() here is a link to the manual.
what you want to do is split the inc string:
$aUserInfo = explode('~', $result['pay_payment_info']);
now you have an array. loop through it and make it like you want:
$result = array();
foreach($aUserInfo as $v){
$aTmp = explode('=',$v);
$result[$aTmp[0]] = $aTmp[1];
}
at the end of this you have an array with keys as keys and their respective values as values, i.e.
$result = array( 'tag' => '6F0000173',
'user'=> 'James',
'tagrole'=> 0 );
The error tells you exactly why it is an error: substring_index is not a valid/native PHP function... you can define your own function of substring_index, though.
However, given the string:
$TAG=6F0000173~$USER=james~$TAGROLE=0
to get the $USER=james part, you can use explode as follows--
$payNo = explode("~", $result["pay_payment_info"])
Now, you have the $USER info in $payNo[1]
If you want to go even further and just get the value of what $USER value is, then you can use PHP's native substr function:
$justUserPart = substr($payNo[1], strpos($payNo[1], "=")+1);
echo $justUserPart;
Please Note: The above assumes that you will always have the string in the format of
$TAG=...~$USER=...~$TAGROLE=...
I have the following preg_replace not preg_replace_callback which uses arrays for search patterns and replacement not only a single value and it works fine:
preg_replace(['/\{/','/\}/','/"(.*?)"/'],['<span class=\'olive\'>{','}</span>','<span class=\'olive\'>${0}</span>'],FoxText::insertBr($model->TafseerText));
However, when I try to pass ${0} to function something like:
preg_replace(['/\{/','/\}/','/"(.*?)"/'],['<span class=\'olive\'>{','}</span>',FoxText::pattern2VerseId("\$0")],FoxText::insertBr($model->TafseerText));
In the FoxText::pattern2VerseId function I try print_r as follows:
public static function pattern2VerseId($txt, $pattern = '/\(((\d+)-(\w+))\)/u')
{
$parts = array_map('trim',explode('-', $txt));
print_r(explode('-', $parts[0]));
return $parts[0].' *'.$parts[0].'|';
}
It prints Array ( [0] => $0 ) while the return value is matched string from the previous call!
In other words, how could it able to return $parts[0] as a string and It could not able to explode this string. Or how could I pass the value correctly to the function to be processed there?
By the way, the string is something like (125-Verse)
Because when you call the function pattern2VerseId you call it with the string $0. And since string $0 doesn't contain any hyphen, the explode just returns an array with single element containing the string.
explode('-', '$0') // will return Array([0] => $0)
By "\$0" are you actually trying to get the first part of the matched regex, i.e. 125 in this case? Because you're not doing it right.
Since I have PHP < 7. i.e there is no preg_replace_callback_array, the only solution that I have able to use is replacing the first pattern(s) using preg_replace then passing the output to one preg_replace_callback
$p = preg_replace(['/\{/','/«/','/\(/','/\}/','/»/','/\)/','/"(.*?)"/'],['<span class=\'olive\'>{','<span class=\'olive\'>«','<span class=\'olive\'>(','}</span>','»</span>',')</span>','<span class=\'olive\'>${0}</span>'],FoxText::insertBr($model->TafseerText));
$callback = function($m){return FoxText::pattern2VerseId($m);};
echo preg_replace_callback('/\(((\d+)-(\w+))\)/u', $callback, $p);
I have the following point: a xls file contains one column with codes. The codes have a prefix and a unique code like this:
- VIP-AX757
- VIP-QBHE6
- CODE-IUEF7
- CODE-QDGF3
- VIP-KJQFB
- ...
How can I get equal parts of strings or an array? perfect would be if I get an array like this:
- $result[VIP] = 3;
- $result[CODE] = 2;
An array with the found prefix and the sum of cells with that prefix. But the result is not so important at the moment.
I couldn't find a soloution how to get equal parts of two strings: how to compare this "VIP-AX757" and "VIP-QBHE6" and get a result that says: "VIP-" is the same prefix/part in this two strings?
Hope someone has an idea.
thx!
-drum roll- Time for a one-liner!
$result = array_count_values(array_map(function($v) {list($a) = explode("-",$v); return $a;},$input));
(Assumes $input is your array of codes)
If you are using PHP 5.4 or newer (you should be), then:
$result = array_count_values(array_map(function($v) {return explode("-",$v)[0];},$input));
Tested in PHP CLI:
If the prefix is always followed by a '-' then you can do something like this:-
foreach ($codes as $code) {
$tmp = explode("-",$code);
$result[$tmp[0]] += 1;
}
print_r($result);
Depends on the variability of the data, but something like:
preg_match_all('/^([^-]+)/m', $string, $matches);
$result = array_count_values($matches[1]);
print_r($result);
If you don't know that there is an - after the prefix but the prefix is always letters then:
preg_match_all('/^([A-Z]+)/im', $string, $matches);
$result = array_count_values($matches[1]);
Otherwise you'll have to define exactly what the prefix can contain if it's not the delimiter.
Since you stated via comment to Niet that you don't have a reliable delimiter, then we can only write a pattern that identifies your targeted substrings based on their location in each line.
I recommend preg_match_all() with no capture group, a start of the line anchor, and a multi-line pattern modifier (m).
I've written a preg_split() alternative, but the pattern is a little "clunkier" because of the way I'm handling the line returns.
Code: (Demo)
$string = 'VIP-AX757
VIP-QBHE6
CODE-IUEF7
CODE-QDGF3
VIP-KJQFB';
var_export(array_count_values(preg_match_all('~^[A-Z]+~m', $string, $out) ? $out[0] : []));
echo "\n\n";
var_export(array_count_values(preg_split('~[^A-Z][^\r\n]+\R?~', $string, -1, PREG_SPLIT_NO_EMPTY)));
Output:
array (
'VIP' => 3,
'CODE' => 2,
)
array (
'VIP' => 3,
'CODE' => 2,
)
I'm trying to figure out how I can compare values from an array against a particular string.
Basically my values look like chrisx001, chrisx002, chrisx003, chrisx004, bob001
I was looking at fnmatch() but I'm not sure this is the right choice, as what I want to do is keep chrisx--- but ignore bob--- so I need to wildcard the last bit, is there a means of doing this where I can be like
if($value == "chrisx%"){/*do something*/}
and if thats possible is it possible to double check the % value as int or similar in other cases?
Regex can tell you if a string starts with chrisx:
if (preg_match('/^chrisx/', $subject)) {
// Starts with chrisx
}
You can also capture the bit after chrisx:
preg_match('/^chrisx(.*)/', $subject, $matches);
echo $matches[1];
You could filter your array to return a second array of only those entries beginning whith 'chris' and then process that filtered array:
$testData = array ( 'chrisx001', 'chrisx002', 'chrisx003', 'chrisx004', 'bob001');
$testNeedle = 'chris';
$filtered = array_filter( $testData,
function($arrayEntry) use ($testNeedle) {
return (strpos($arrayEntry,$testNeedle) === 0);
}
);
var_dump($filtered);
I have this string:
a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}
I want to get number between "a:" and ":{" that is "3".
I try to user substr and strpos but no success.
I'm newbie in regex , write this :
preg_match('/a:(.+?):{/', $v);
But its return me 1.
Thanks for any tips.
preg_match returns the number of matches, in your case 1 match.
To get the matches themselves, use the third parameter:
$matches = array();
preg_match(/'a:(\d+?):{/', $v, $matches);
That said, I think the string looks like a serialized array which you could deserialize with unserialize and then use count on the actual array (i.e. $a = count(unserialize($v));). Be careful with userprovided serialized strings though …
If you know that a: is always at the beginning of the string, the easiest way is:
$array = explode( ':', $string, 3 );
$number = $array[1];
You can use sscanfDocs to obtain the number from the string:
# Input:
$str = 'a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}';
# Code:
sscanf($str, 'a:%d:', $number);
# Output:
echo $number; # 3
This is often more simple than using preg_match when you'd like to obtain a specific value from a string that follows a pattern.
preg_match() returns the number of times it finds a match, that's why. you need to add a third param. $matches in which it will store the matches.
You were not too far away with strpos() and substr()
$pos_start = strpos($str,'a:')+2;
$pos_end = strpos($str,':{')-2;
$result = substr($str,$pos_start,$pos_end);
preg_match only checks for appearance, it doesn't return any string.