0

I have a string which returns data usage in B, KB, MB and so on. I want to separate the number and string part of it.

Ex : 14.5 MB - I want 14.5 and MB separately.

I tried using regex

'/(\d+)(\w)/'

but does not give the desired result.

Expected result

Array( [0] => 14.5, [1] => 'MB' )
Dilani
  • 533
  • 1
  • 6
  • 22

2 Answers2

2

You may try using preg_match_all here with the following regex pattern:

\b(\d+(?:\.\d+)?)\s*([KMGT]?B)\b

This matches a (possibly) decimal size, followed by a unit based in bytes.

$input = "Here are three sizes 14.5 MB, 10B, and 30.8 GB";
preg_match_all("/\b(\d+(?:\.\d+)?)\s*([KMGT]?B)\b/", $input, $matches);
print_r($matches[1]);
print_r($matches[2]);

This prints:

Array
(
    [0] => 14.5
    [1] => 10
    [2] => 30.8
)
Array
(
    [0] => MB
    [1] => B
    [2] => GB
)
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

You can make use of explode function if you are sure that your string will always contains space in between

$consumedData = '14.5 MB';
$withSeperate = explode(' ',$consumedData);
var_dump($withSeperate);

Output

Array([0] => 14.5, [1] => 'MB'); 
BlackXero
  • 880
  • 4
  • 17