开发者

Search for numbers < 4 characters and start with "0", then delete the starting zeros, PHP

开发者 https://www.devze.com 2023-02-13 16:23 出处:网络
I have a .txt file of approx 4000 lines of numbers and text, e.g : 01004 text 002 04122 text 242 76079 text 040

I have a .txt file of approx 4000 lines of numbers and text, e.g :

01004 text 002
04122 text 242
76079 text 040
82752 text 032e
...

What I want to do 开发者_如何学Cis to remove all the zeros at the beginning of all numbers that is less than 4 characters long so that the list will become

01004 text 2
04122 text 242
76079 text 40
82752 text 32e
...

Any help will be greatly appreciated :)


    $path = 'foo.txt';
    $file = file_get_contents($path);
    $file = preg_replace('/ 0+/', ' ', $file);
    file_put_contents($path, $file);


$path = 'foo.txt';
$file = file_get_contents($path);
$file = preg_replace('/([^0-9])0+([0-9]{0,3}[^0-9])/', '$1$2', $file);
file_put_contents($path, $file);

This will make sure you delete only for numbers less than or equal to four characters.


<?php

$read  = fopen( 'foo.txt', 'r' );
$write = fopen( 'foo_conv.txt', 'w' );

while ( !feof( $read ) ) 
{
    fwrite(
        $write,
        preg_replace(
            '(^([0-9]+ .* )0*([^0 ]+))',
            '$1 $2',
            fgets( $read, 1024 )
        )   
    );  
}

fclose( $read );
fclose( $write );

?>

This will remove leading 0s only from the last number in the line and does not require to load the full file into memory.


Using only preg_replace is an ugly way to do this because it would get out of hand very quickly, but since we're only worried about cases of a 0 followed by 1 or 2 digits or 00 followed by one digit, it's not too horrid...

$str = preg_replace('/(?<!\d)0(?:([1-9]\d?)|0([1-9]))(?!\d)/', '$1$2', $str);

To scale it though, you should probably do something more like:

$str = preg_replace_callback('/(?<!\d)(\d{1,3})(?!\d)/', parseNum, $str);

function parseNum($matches) {
    return intval($matches[1]);
}
0

精彩评论

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

关注公众号