Question

I need help in keeping just the number in the RIGHT (before the zeros) In this example:

$var = 'LMO0000000381W' => keep just 381

I started with substr($var, 3, -1); which give me 0000000381 but it's the zeros that might be inside other numbers that bothers me. those are cases I need to be valid

0000000381 => 381
0000003081 => 3081
0000030810 => 30810
0000053081 => 53081
Was it helpful?

Solution 2

Once you've extracted the number, which is the difficult part, almost anything will do:

<?php

$data = '0000000381';
var_dump( (int)$data );
var_dump( (float)$data );
var_dump( number_format($data) );
var_dump( sprintf('%d', $data) );

... prints:

int(381)
float(381)
string(3) "381"
string(3) "381"

Edit: if you want some other ideas, here's a not fully tested regular expression:

$var = 'LMO0000000381W';
if( preg_match('/^[A-Z]*0*([0-9]+)[A-Z]*$/i', $var, $matches) ){
    var_dump($matches[1]);
}

But your system is just fine.

OTHER TIPS

Given $var = 'LMO0000000381W' with the letters, this should do it:

echo preg_replace('/[^1-9]*([0-9]*)/', '$1', $var);

Or:

preg_match('/[1-9]\d+/', $var, $matches);
echo $matches[0];

We have these two methods to do this

1.Using ltrim function of PHP

$str = ltrim($str, '0');

2.Using typecast

 `(string)((int)"00000234892839")`
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top