I am trying to extract a part of the string 0044800 999999
at the first occurrence of a non-zero. I am using preg_split() thus:
$str = preg_split("/[1-9]/", "0044800 999999", 2);
var_dump($str[1]);
The problem is that when this operation completes, it also removes the matching non-zero digit. E.g.
0044800 999999
results in 4800 999999
instead of 44800 999999
.
What could I be doing wrong?
CodePudding user response:
You could on optional leading zeroes
$str = preg_split("/^0*/", "0044800 999999", 2);
var_dump($str[1]);
Output
string(12) "44800 999999"
Or you could split on 1 or more leading zeroes, and check if the returned array has 2 parts in case the string did not contain leading zeroes.
You might use a more precise approach removing leading zeroes, and use a capture group to match digits followed by a space and digits.
$re = '/^0*(\d (?:\h \d )*)$/';
$str = '0044800 999999';
$result = preg_replace($re, '$1', $str);
var_dump($result);
Output
string(12) "44800 999999"