سؤال

need a little help with a small issue of string splitting.

I'm trying to split a serial number into two, do some calculations on the second half and join it back to the first half. My problem is the second half starts with two zeros and PHP removes the leading zeros.

I think keeping the variables as strings will keep the zeros but I can't seem to find a way to split the serial number into smaller strings, all the methods I try split them into an array. Here is a part of my code;

$info1 = nkw549blc003i00021; //this is the serial number.

I want to split $info1 into;

$number1 = nkw549blc003i0

$number2 = 0021

then use for loop on $number2 like

$num = 1;
for ($num=1; $num < $unitsquantity[$key] ; $num++) {
  $sum = $number2+$num;
  $final=$number1.$sum;
  echo "$final<br>";
}

Any help is greatly appreciated.

هل كانت مفيدة؟

المحلول 3

Strings are array chars, so you can get each char of them by iterating through their length

define('SERIAL_NUM_LEN', 4);
$info1 = 'nkw549blc003i00021';
$number1 = ''; $number2 = '';
for ($i = 0; $i < strlen($info1)-SERIAL_NUM_LEN; $i++) {
    $number1 .= $info1[$i];
}
for ($i = strlen($info1)-SERIAL_NUM_LEN; $i < strlen($info1); $i++) {
    $number2 .= $info1[$i];
}

var_dump($number1, $number2);

Output:

string 'nkw549blc003i0' (length=14)

string '0021' (length=4)

This way you can skip whichever chars from the string you want if you want to build totally different string. Or add chars in the middle.

نصائح أخرى

$info1 = 'nkw549blc003i00021';

$number1 = substr($info1, 0, -4);
$number2 = sprintf('%1$04d', substr($info1, -4, 4));

If the string will always be 4 chars long, you can use str_pad

for ($num=1; $num < $unitsquantity[$key] ; $num++) {
  echo $number1 . str_pad($number2+$num, 4, '0', STR_PAD_LEFT);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top