This question already has answers here:
Get last whole number in a string
(7 answers)
Closed 6 months ago.
I have this string #22aantal283xuitvoeren.
What is the best way to find the last numeric value in a string? (283 in this case)
I don't think chop() or substr() is the wat to go.
You can use preg_match_all and match all digits.
Then the last item in the array is the last number in the string.
$s = "#22aantal283xuitvoeren";
preg_match_all("/\d+/", $s, $number);
echo end($number[0]); // 283
https://3v4l.org/44VUJ
You could try preg_match_all():
$string = "#22aantal283xuitvoeren";
$result = preg_match_all(
"/(\d+)/",
$string,
$matches);
$lastNumericValueInString = array_pop($matches[1]);
echo $lastNumericValueInString;
Echoes 283
Here is a solution without regex.
Basically loop from back to front until the first number is found. Then, loop until the first non-number is found.
$string = "#22aantal283xuitvoeren";
for($i = strlen($string) - 1; $i >= 0; --$i) {
if(is_numeric($string[$i])) {
// found the first number from back to front
$number = $string[$i];
while(--$i >= 0 && is_numeric($string[$i])) {
$number = $string[$i].$number;
}
break;
}
}
// $number is now "283"
// if you want an integer, use intval($number)
Related
This question already has answers here:
Get the sum of all digits in a numeric string
(13 answers)
Closed 8 months ago.
I'm trying to adding all numbers from last 6 digit from substr(). Let say the number is 19283774616, I'm trying to have result from this: 7+7+4+6+1+6 = ?. Here is my current code
public function accountHash($accountNumber)
{
$result = 0;
$accountNumber = substr($accountNumber, -6);
for($i=0; $i<=strlen($accountNumber); $i++) {
$result += substr($accountNumber, $i, 1); // A non-numeric value encountered here
}
echo $result;
}
From the function above, "A non-numeric value encountered" error occurred. Need suggestion on how to do this. Thank you
You attempt to get more characters than string contains. Replace "<=" with "<" in your condition expression, i.e. change:
for($i=0; $i<=strlen($accountNumber); $i++) {
to
for($i=0; $i<strlen($accountNumber); $i++) {
You need to use < instead of <= in your for loop.
And you can do it a more simple way,
$result = 0;
for($i = 0; $i < 6; $i++){
$result += $string[-$i];
}
An alternative method without loops (or error checking, for what it's worth):
function accountHash($accountNumber)
{
return array_sum(
preg_split('//u', mb_substr($accountNumber, -6), null, PREG_SPLIT_NO_EMPTY)
);
}
Demo
This question already has answers here:
Break long string into pieces php
(5 answers)
Closed 3 years ago.
I want to make a program which splits a long number into pieces of 13 digited number such that I can loop for every 13 digits just using php.
$number = 012345678901230123456789123
Should output
0123456789123
0123456789123
And it should be for any large number having the number of digit multiple of 13.It looks about looping and algorithm but I want to make it as short as possible and I have doubts on how to do it. So I am just asking about the main concept.
The most dynamic solution is probably to use array_functions on the string.
So str_split to make it array then chunk it in size 13 and implode the arrays.
$number = "012345678901230123456789123";
$arr = array_chunk(str_split($number), 13);
foreach($arr as &$val){
$val = implode($val);
}
https://3v4l.org/LsNFt
You can create a function where you can use your string and size as parameter and return an array of strings of the desired length:
function splitString($str, $packetSize) {
$output = [];
$size = strlen($str);
for ($i = 0; $i < $size; $i += $packetSize) {
if ($i + $packetSize < $size) {
$output[]= substr($str, $i, $packetSize);
} else {
$output[]=substr($str, $i);
}
}
return $output;
}
I have a string formed up by numbers and sometimes by letters.
Example AF-1234 or 345ww.
I have to get the numeric part and increment it by one.
how can I do that? maybe with regex?
You can use preg_replace_callback as:
function inc($matches) {
return ++$matches[1];
}
$input = preg_replace_callback("|(\d+)|", "inc", $input);
Basically you match the numeric part of the string using the regex \d+ and replace it with the value returned by the callback function which returns the incremented value.
Ideone link
Alternatively this can be done using preg_replace() with the e modifier as:
$input = preg_replace("|(\d+)|e", "$1+1", $input);
Ideone link
If the string ends with numeric characters it is this simple...
$str = 'AF-1234';
echo $str++; //AF-1235
That works the same way with '345ww' though the result may not be what you expect.
$str = '345ww';
echo $str++; //345wx
#tampe125
This example is probably the best method for your needs if incrementing string that end with numbers.
$str = 'XXX-342';
echo $str++; //XXX-343
Here is an example that worked for me by doing a pre increment on the value
$admNo = HF0001;
$newAdmNo = ++$admNo;
The above code will output HF0002
If you are dealing with strings that have multiple number parts then it's not so easy to solve with regex, since you might have numbers overflowing from one numeric part to another.
For example if you have a number INV00-10-99 which should increment to INV00-11-00.
I ended up with the following:
for ($i = strlen($string) - 1; $i >= 0; $i--) {
if (is_numeric($string[$i])) {
$most_significant_number = $i;
if ($string[$i] < 9) {
$string[$i] = $string[$i] + 1;
break;
}
// The number was a 9, set it to zero and continue.
$string[$i] = 0;
}
}
// If the most significant number was set to a zero it has overflowed so we
// need to prefix it with a '1'.
if ($string[$most_significant_number] === '0') {
$string = substr_replace($string, '1', $most_significant_number, 0);
}
Here's some Python code that does what you ask. Not too great on my PHP, but I'll see if I can convert it for you.
>>> import re
>>> match = re.match(r'(\D*)(\d+)(\D*)', 'AF-1234')
>>> match.group(1) + str(int(match.group(2))+1) + match.group(3)
'AF-1235'
This is similar to the answer above, but contains the code inline and does a full check for the last character.
function replace_title($title) {
$pattern = '/(\d+)(?!.*\d)+/';
return preg_replace_callback($pattern, function($m) { return ++$m[0]; }, $title);
}
echo replace_title('test 123'); // test 124
echo replace_title('test 12 3'); // test 12 4
echo replace_title('test 123 - 2'); // test 123 - 3
echo replace_title('test 123 - 3 - 5'); // test 123 - 3 - 6
echo replace_title('123test'); // 124test
I have a string formed up by numbers and sometimes by letters.
Example AF-1234 or 345ww.
I have to get the numeric part and increment it by one.
how can I do that? maybe with regex?
You can use preg_replace_callback as:
function inc($matches) {
return ++$matches[1];
}
$input = preg_replace_callback("|(\d+)|", "inc", $input);
Basically you match the numeric part of the string using the regex \d+ and replace it with the value returned by the callback function which returns the incremented value.
Ideone link
Alternatively this can be done using preg_replace() with the e modifier as:
$input = preg_replace("|(\d+)|e", "$1+1", $input);
Ideone link
If the string ends with numeric characters it is this simple...
$str = 'AF-1234';
echo $str++; //AF-1235
That works the same way with '345ww' though the result may not be what you expect.
$str = '345ww';
echo $str++; //345wx
#tampe125
This example is probably the best method for your needs if incrementing string that end with numbers.
$str = 'XXX-342';
echo $str++; //XXX-343
Here is an example that worked for me by doing a pre increment on the value
$admNo = HF0001;
$newAdmNo = ++$admNo;
The above code will output HF0002
If you are dealing with strings that have multiple number parts then it's not so easy to solve with regex, since you might have numbers overflowing from one numeric part to another.
For example if you have a number INV00-10-99 which should increment to INV00-11-00.
I ended up with the following:
for ($i = strlen($string) - 1; $i >= 0; $i--) {
if (is_numeric($string[$i])) {
$most_significant_number = $i;
if ($string[$i] < 9) {
$string[$i] = $string[$i] + 1;
break;
}
// The number was a 9, set it to zero and continue.
$string[$i] = 0;
}
}
// If the most significant number was set to a zero it has overflowed so we
// need to prefix it with a '1'.
if ($string[$most_significant_number] === '0') {
$string = substr_replace($string, '1', $most_significant_number, 0);
}
Here's some Python code that does what you ask. Not too great on my PHP, but I'll see if I can convert it for you.
>>> import re
>>> match = re.match(r'(\D*)(\d+)(\D*)', 'AF-1234')
>>> match.group(1) + str(int(match.group(2))+1) + match.group(3)
'AF-1235'
This is similar to the answer above, but contains the code inline and does a full check for the last character.
function replace_title($title) {
$pattern = '/(\d+)(?!.*\d)+/';
return preg_replace_callback($pattern, function($m) { return ++$m[0]; }, $title);
}
echo replace_title('test 123'); // test 124
echo replace_title('test 12 3'); // test 12 4
echo replace_title('test 123 - 2'); // test 123 - 3
echo replace_title('test 123 - 3 - 5'); // test 123 - 3 - 6
echo replace_title('123test'); // 124test
This question already has answers here:
Get the sum of all digits in a numeric string
(13 answers)
Closed 5 years ago.
I am getting o/p like "11111" and I want to sum all these digits that should become 5. But if I use count count it is showing one only i.e, 1.Rather it should show 5.
Below is my code,
$count = count($inventory['product_id']);
$product_total = $count;
echo $product_total;//o/p => 1.
I need echo $product_total;//o/p => 5.
You can use the following using str_split to get an array with all characters (in your case digits) and using array_sum to get the sum of all the digits:
$digits = "11112";
$arrDigits = str_split($digits);
echo array_sum($arrDigits); //6 (1 + 1 + 1 + 1 + 2)
Demo: https://ideone.com/tZwi9J
Count is used for counting array elements.
What you can do in PHP, is to iterate over a string using either a foreach (not 100% sure) or for loop for this and accessing the elements like array elements by their index:
$str = '111111123545';
$sum = 0;
for ($i = 0; $i < strlen($str); $i++) {
$sum += intval($str[$i]);
}
print $sum; // prints 26
Alternativly, you can split the string using no delimiter and using the array_sum() function on it:
$str = '111111123545';
$sum = array_sum(str_split($str));
print $sum; // prints 26
array_sum(str_split($number));
Another possible way to count the list of digits in PHP is:
// match only digits, returns counts
echo preg_match_all( "/[0-9]/", $str, $match );
// sum of digits
echo array_sum($match[0]);
Example:
$ php -r '$str="s12345abas"; echo "Count :".preg_match_all( "/[0-9]/", $str, $match ).PHP_EOL; echo "Sum :".array_sum($match[0]).PHP_EOL;'
Count :5
Sum :15