user1856596
user1856596

Reputation: 7243

Sanitize number by removing first digit then any consecutive zeros

I have an array of numbers, for example:

10001234
10002345

Now I have a number, which should be matched against all of those numbers inside the array. The number could either be 10001234 (which would be easy to match), but it could also be 100001234 (4 zeros instead of 3) or 101234 (one zero instead of 3) for example. Any combination could be possible. The only fixed part is the 1234 at the end.

I can't simply isolate the last 4 chars, because the needed value can sometimes be 3 or 5 or 6 digits in length (like 1000123456).

Upvotes: 0

Views: 51

Answers (3)

SDC
SDC

Reputation: 14212

The question doesn't make the criteria for the match very clear. However, I'll give it a go.

First, my assumptions:

  • The number always starts with a 1 followed by an unknown number of 0s.

  • After that, we have a sequence of digits which could be anything (but presumably not starting with zero?), which you want to extract from the string?

Given the above, we can formulate an expression fairly easily:

$input='10002345';
if(preg_match('/10+(\d+)/',$input,$matches)) {
     $output = $matches[1];
}

$output now contains the second part of the number -- ie 2345.

If you need to match more than just a leading 1, you can replace that in the expression with \d to match any digit. And add a plus sign after it to allow more than one digit here (although we're still relying on there being at least one zero between the first part of the number and the second).

$input='10002345';
if(preg_match('/\d+0+(\d+)/',$input,$matches)) {
     $output = $matches[1];
}

Upvotes: 0

mohammad mohsenipur
mohammad mohsenipur

Reputation: 3149

if always the first number is one you can use this

$Num=1000436346;
echo(int)ltrim($Num."","1");

output:

436346

Upvotes: 2

Madara's Ghost
Madara's Ghost

Reputation: 175048

$number % 10000

Will return the remainder of dividing a number by 10000. Meaning, the last four digits.

Upvotes: 0

Related Questions