I have a long string like below:
$string = "age1:32,age2:25,age3:52,..."
Now I want to extract the age numbers in this string and then add the numbers together and determine the average age.
I was able to extract the numbers with the help of the following code
$numbers = preg_replace('/[^0-9]/', '', $string );
but the output I get is like this and I cannot add the numbers together.
output:
322552
Using preg_match_all to find all age values followed by array_sum to find the total/average we can try:
$string = "age1:32,age2:25,age3:52,...";
preg_match_all("/age\d+:(\d+)/", $string, $matches);
print_r(array_sum($matches[1]) / count($matches[1])); // 36.333333333333
Restart the fullstring match after each colon, then match one or more digits.
preg_match_all() returns the number of matches ($count).
Divide the sum of the matches by the number of matches.
Code: (Demo)
$string = "age1:32,age2:25,age3:52,...";
$count = preg_match_all('/:\K\d+/', $string, $m);
echo array_sum($m[0] ?? []) / $count;
// 36.333333333333
If you wanted to grab all numbers, just use \d+. (Demo)
$string = "available12available15available22available11...";
$count = preg_match_all('/\d+/', $string, $m);
echo array_sum($m[0] ?? []) / $count;
Related
how to highlight last 3 number in the string:
ab9c5lek94ke72koe8nsk9
i want output:
ab9c5lek94ke72koe8nsk9
i tried following:
$str = "ab9c5lek94ke72koe8nsk9";
$numbers = preg_replace('/[^0-9]/', '', $str );
$last3 = substr($numbers, -3);
$highlights = str_split($last3);
$output = preg_replace('/'.implode('|', $highlights).'/i', '<b>$0</b>', $str);
but it highlight:
ab9c5lek94ke72koe8nsk9
You can achieve that easily using regular expression with PHP's preg_replace() function. Just find last 3 digits 3 times at the end of the string. See the following code:
$str1 = 'ab9c5lek94ke2koe8nsk9';
$str2 = 'dag2vue41a89au76zhz30';
echo preg_replace('/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/mui', '<b>$1</b>$2<b>$3</b>$4<b>$5</b>$6', $str1);
echo preg_replace('/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/mui', '<b>$1</b>$2<b>$3</b>$4<b>$5</b>$6', $str2);
Outputs
ab9c5lek94ke2koe8nsk9
and
dag2vue41a89au76zhz30
You can have a regex like below:
/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/
which is basically (\d)([^\d]*) 3 times with a $ sign at the end. It means we are matching a digit followed by 0 or more non digit characters. Note that we do need the $ sign at the end to match only last 3 digits.
Snippet:
<?php
$str = "ab9c5lek94ke2koe8nsk9";
echo preg_replace('/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/',"<b>$1</b>$2<b>$3</b>$4<b>$5</b>$6",$str);
Demo: https://3v4l.org/PoYCG
The replacement string is just having the bold tags with group number of the matched strings which are to be highlighted.
You can split the string on the 3rd from last number, then highlight everything in that sub string and then recombine the substrings.
In my example, I get all of the numbers in the string and put them in array. Then I use that array to get the delimiter (72 in your example), then use that to split the string into two arrays, at that point you can highlight everything in array[1] and then combine it back into array[0]
$str = "ab9c5lek94ke72koe8nsk9";
// get all of the numbers in order and place into it's own array
$numbers = trim(preg_replace('/[^0-9]/', ' ', $str ));
$numbers = preg_split('/\s+/', $numbers);
// using that get the delimiter to where to split the string. and split.
$delim = $numbers[count($numbers)-3];
$arr = explode($delim, $str);
$arr[1] = $delim . $arr[1];
// then highlight everything in $arr[1]
// then combine $arr[0] and $arr[1]
I have a string as follows...
$myString = "2,4,5,8,9,11,Inventory2,Inventory3,Inventory4,Inventory5"
I want to search for anything with the prefix "Inventory" and replace with a number which is dynamically generated. As an example say the number is "24 it will add 24 to 2 making the first matching result 26.
The end result should turn the string to "2,4,5,8,9,11,26,27,28,29"
I know how to search and replace inventory however I am unable to figure out how to add to the trailing number. Thoughts?
$str = "$comma_separated";
$expression = 'Inventory(\*),';
$replace = '24';
$newStr = str_replace("Inventory","24","$comma_separated");
I am using a static number for testing purposes
preg_replace_callback can do it:
$v = 24;
$myString = "2,4,5,8,9,11,Inventory2,Inventory3,Inventory4,Inventory5";
echo preg_replace_callback(
'/Inventory(\d+)/',
function ($m) use ($v) {
return $v + $m[1];
},
$myString
);
I have a query string stored in a variable and I need to strip out some stuff from it using preg_replace()
the parameters I want to strip out look like this:
&filtered_features[48][]=491
As there will be multiples of these parameters in the query string the 48 and the 491 can be any number so the regex needs to essentially match this:
'&filtered_features[' + Any number + '][]=' + Any number
Anyone know how I would do this?
$string = '&filtered_features[48][]=491';
$string = preg_replace('/\[\d+\]\[\]=\d+/', '[][]=', $string);
echo $string;
I assume you wanted to remove the numbers from the string. This will match a multi-variable query string as well since it just looks for [A_NUMBER][]=A_NUMBER and changes it to [][]=
$query_string = "&filtered_features[48][]=491&filtered_features[49][]=492";
$lines = explode("&", $query_string);
$pattern = "/filtered_features\[([0-9]*)\]\[\]=([0-9]*)/";
foreach($lines as $line)
{
preg_match($pattern, $line, $m);
var_dump($m);
}
/\&filtered_features\[(?<n1>\d*)\]\[\]\=(?<n2>\d*)/'
this will match first number in n1 and second in n2
preg_match_all( '/\&filtered_features\[(?<n1>\d*)\]\[\]\=(?<n2>\d*)/', $str, $matches);
cryptic answer will replace more than necessary with this string:
&something[1][]=123&filtered_features[48][]=491
I am trying to filter out all characters before the first / sign. I have strings like
ABC/123/...
and I am trying to filter out ABC, 123 and ... into separate strings. I have alsmost succeeded with the parsing of the first letters before the / sign except that the / sign is part of the match, which I donĀ“t want to.
<?php
$string = "ABC/123/...";
$pattern = '/.*?\//';
preg_match($pattern, $string, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
The letters before the first/ can differ both in length and characters, so a string could also look like EEEE/1111/aaaa.
If you are trying to split the string using / as the delimiter, you can use explode.
$array = explode("/", $string);
And if you are looking only for the first element, you can use array_shift.
$array = array_shift(explode("/", $string));
I have a string, consisting of:
some numbers,
a single letter,
some numbers and letters.
For example: 987342j34kj3
I want to output something like:
$numbers = 987342
$letter = j
$restofit = 34kj3
Any idea how to do this with PHP? Can I use preg_match?
No problem:
preg_match('/(\d+)([a-z])([a-z0-9]+)/', $string, $matches);
// First element of $matches is the entire matched string, ignore it
list(, $numbers, $letter, $restofit) = $matches;