Replacing random numbers in a php string serial numbers(123...) - php

In PHP, how to convert a string containing mixture of random letters and numbers to a string containing serial numbers along with random numbers without changing their position in a string? For example,
$str_a = "1)Apple 5)Ball 3)Cat 8)Dog 4)Egg";
Now, I want to convert this string into
$str_b = "1)Apple 2)Ball 3)Cat 4)Dog 5)Egg";
I want the numbers 1,5,3,8,4 to be 1,2,3,4,5.

This should work for you:
Just use preg_replace_callback() and replace each digit (\d+ => 0-9 as many times as possible) with an incrementing number, .e.g
<?php
$str_a = "1)Apple 5)Ball 3)Cat 8)Dog 4)Egg";
$start = 1;
echo $newStr = preg_replace_callback("/\d+/", function($m)use(&$start){
return $start++;
}, $str_a);
?>
output:
1)Apple 2)Ball 3)Cat 4)Dog 5)Egg

Created Simple looping program:
$str_a = "1)Apple 5)Ball 3)Cat 8)Dog 4)Egg";
function change($str_a) {
$counter = 1;
for($i=0; $i<strlen($str_a); $i++) {
if(is_numeric($str_a[$i])) {
$str_a[$i] = $counter++;
}
}
return $str_a;
}
print(change($str_a))
Output:
1)Apple 2)Ball 3)Cat 4)Dog 5)Egg

You can use preg_split and then concatenate it incrementing by 1. This will work also for numbers consisting of multiple digits:
$str_a = "51)Apple 675)Ball 334)Cat 84)Dog 904)Egg";
$a = preg_split('/\b\d+/', $str_a);
$str_b = '';
for($i=0,$c = count($a);$i<$c;$i++){
if($i){
$str_b .= $i.$a[$i];
}
}
echo $str_b;
Output:
1)Apple 2)Ball 3)Cat 4)Dog 5)Egg

Related

Using preg_replace() To Increment a Digit in a Phrase [duplicate]

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

adding an increment to a variable [duplicate]

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

Generate random between alphanumeric min and max in PHP

I am looking for an approach like mt_rand to generate a random value, but between two alphanumeric values instead of integers.
For example, rand(g3j3j4k5, z9kDDkks8f8d).
I tried to convert the alphanumeric values to integers by base_convert. Beside the fact, it is somehow overkill, sometimes the integer is more than 15 digits, and thus not working in PHP rand functions.
NOTE: It is not about making a random string with given length. The value should between two given values, exactly like a random number between min and max integers.
This should work for you:
Here I split $min and $max into an array with str_split() and loop through each character of both arrays with array_map().
There I get the position of the character with strpos() and return a random alphanum character in that particular range. If min is bigger than max I just return a random character from the entire range.
Code:
<?php
function alphanum_rand($min = "", $max = ""){
$chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$random = array_map(function($minC, $maxC)use($chars){
if(($minKey = strpos($chars, $minC)) < ($maxKey = strpos($chars, $maxC)))
return $chars[mt_rand($minKey, $maxKey)];
else
return $chars[mt_rand(0, strlen($chars))];
}, str_split($min), str_split($max));
return implode("", $random);
}
echo alphanum_rand("g3j3j4k5", "z9kDDkks8f8d");
?>
You could try a simple PHP Function and define a random string alpha numeric and can also include special characters. For loop will do the magic for u :)
function RandomString($size)
{
$chars = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$string = array();
$alphaLength = strlen($chars) - 1;
for ($i = 0; $i < $size; $i++) {
$n = rand(0, $alphaLength);
$string[] = $chars[$n];
}
return implode($string);
}
and simple call it with the size you need.
<?php
echo RandomString(5); // Length of strings
?>

PHP: Generating random string with both suffix and prefix as capital letters

Hie guys i want to create a random string of numbers where there is a fixed letter B at the beginning and a set of eight integers ending with any random letter, like for example B07224081A where A and the other numbers are random. This string should be unique. How can I do this?
Do you mean something like this?
$letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$numbers = rand(10000000, 99999999);
$prefix = "B";
$sufix = $letters[rand(0, 25)];
$string = $prefix . $numbers . $sufix;
echo $string; // printed "B74099731P" in my case
The more characters - the greater chance to generate unique string.
I think that's much better method to use uniqid() since it's based on miliseconds. Uniqueness of generated string is guaranteed.
This should work for you.
$randomString = "B";
for ($i = 0; $i < 9; $i++) {
if ($i < 8) {
$randomString.=rand(0,9);
}
if ($i == 8) {
$randomString.=chr(rand(65,90));
}
}
echo $randomString;

How to generate an alphanumeric incrementing id in PHP?

I have system in PHP in which I have to insert a Number which has to like
PO_ACC_00001,PO_ACC_00002,PO_ACC_00003.PO_ACC_00004 and so on
this will be inserted in Database for further reference also "PO and ACC" are dynamic prefix they could different as per requirement
Now my main concern is how can is increment the series 00001 and mantain the 5 digit series in the number?
>> $a = "PO_ACC_00001";
>> echo ++$a;
'PO_ACC_00002'
You can get the number from the string with a simple regex, then you have a simple integer.
After incrementing the number, you can easily format it with something like
$cucc=sprintf('PO_ACC_%05d', $number);
Create a helper function and a bit or error checking.
/**
* Takes in parameter of format PO_ACC_XXXXX (where XXXXX is a 5
* digit integer) and increment it by one
* #param string $po
* #return string
*/
function increment($po)
{
if (strlen($po) != 12 || substr($po, 0, 7) != 'PO_ACC_')
return 'Incorrect format error: ' . $po;
$num = substr($po, -5);
// strip leading zero
$num = ltrim($num,'0');
if (!is_numeric($num))
return 'Incorrect format error. Last 5 digits need to be an integer: ' . $po;
return ++$po;
}
echo increment('PO_ACC_00999');
Sprintf is very useful in situations like this, so I'd recommend reading more about it in the documentation.
<?php
$num_of_ids = 10000; //Number of "ids" to generate.
$i = 0; //Loop counter.
$n = 0; //"id" number piece.
$l = "PO_ACC_"; //"id" letter piece.
while ($i <= $num_of_ids) {
$id = $l . sprintf("%05d", $n); //Create "id". Sprintf pads the number to make it 4 digits.
echo $id . "<br>"; //Print out the id.
$i++; $n++; //Letters can be incremented the same as numbers.
}
?>

Categories