Re: Splitting a string

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 




On Thursday 16 November 2006 01:38, Paul Novitski wrote:
> If you need to left-pad with zeroes, PHP comes to the rescue:
> http://php.net/str_pad
>
> However, if you're using the regular expression
> method then you might not need to pad the
> number.  You can change the pattern from this:
>
>          /(\d+)(\d{2})(\d{2})$/'
> to this:
>          /(\d*)(\d{2})(\d{2})$/'

At 11/16/2006 03:23 PM, Børge Holen wrote:
Cool solution, and it works.  =D
I do however need some chars to fill in on the finished product for the look
of it all, so the 0 is needed... Witch is a bit of a shame with this cool
string.


Well, just to make sure you don't discard regexp unnecessarily...

// the pattern guarantees five digits, then two, then two:
$sPattern = '/(\d{5})(\d{2})(\d{2})$/';

// prepend 9 zeroes to the number to enforce the minimum requirements:
preg_match($sPattern, '000000000' . $iNumber, $aMatches);

Results:

$iNumber = '';
$aMatches:
(
    [0] => 000000000
    [1] => 00000
    [2] => 00
    [3] => 00
)

$iNumber = '123';
$aMatches:
(
    [0] => 000000123
    [1] => 00000
    [2] => 01
    [3] => 23
)

$iNumber = '12345';
$aMatches:
(
    [0] => 000012345
    [1] => 00001
    [2] => 23
    [3] => 45
)

$iNumber = '123456789';
$aMatches:
(
    [0] => 123456789
    [1] => 12345
    [2] => 67
    [3] => 89
)


Paul
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux