开发者

php how to remove leading zeros from a CSV?

Ok, let's say I have a string that is CSV: 01,02,05,10,11,13.. what would be 开发者_开发百科the easiest way to remove the leading zeros?


If they are all integers, explode it into an array and convert all to ints.

$values = array_map('intval', explode(',', $csv));


A bit lo-fi, but using ltrim should do the trick:

$zeroLess = ltrim('01', '0');

Alternatively (and substantially more correctly), use intval as follows:

$zeroLess = intval('01');


You could cast all your numbers to ints:

$list = explode(',', $csv_string);
foreach ($list as &$n) $n = (int)$n;
$fixed = implode(',', $list);

Make sure to note that & in the foreach, which lets you modify the actual list elements.


<?
$tdata=explode(',','01,02,05,10,11,13');
foreach ($tdata as $number) {
    $csv[]=number_format($number,0);
}
$csv=implode(',',$csv);
echo $csv;

tested: http://www.ideone.com/lrh8q

edit

Looking at some of the other posts, casting to int instead of number_format is probably faster.


Use preg_replace for this:

$text = "01,02,05,10,11,13,101"; 
echo preg_replace('/(?<=,|\b)0([0-9])/', "$1", $text);

EDIT: Updated the regex to work with numbers with a 0 in the middle of them. (i.e. 101)
Thanks to @BoltClock for helping fix the regex.

Output:

1,2,5,10,11,13,101

The advantage to doing it this way is you don't have to mess with turning all the text into an array, modifying it/looping through it, and then turning it back into text.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜