简体   繁体   中英

Find and split a string by the first character that is not 0

I wanted to know how I could split a string based on the first character that is not 0, eg

$ID = ABC-000000160810;

I want to split the id so it looks like this:

$split_ID = 160810;

I tried to just get the last 6 digits, however the problem was that the 6 digits might not always be consistent, so just need to split based on the first non-zero. What is the easiest way to achieve this?

Thanks.

Here's a way using a regular expression:

$id = 'ABC-000000160810';
preg_match('/-0*([1-9][0-9]*)/', $id, $matches);
$split_id = $matches[1];

You can use ltrim if you only want to remove leading zeroes.

$ID = ABC-000000160810;
$split_ID = ltrim($str, '0');

Use ltrim to remove leading characters.

$id = 'ABC-00001234';
$numeric = ltrim(mb_substr($id, mb_strpos($id, '-') + 1), '0');
echo $numeric; // 1234

The above requires the mbstring extension to be enabled. If you encounter an error, either enable the extension or use the non-multibyte functions substr and strpos . Probably you should get in the habit of using the mb_ string functions.

This should also work:

const CHAR_MASK = 'a..zA..Z-0';
$id = 'ABC-00001234';
$numeric = ltrim($id, CHAR_MASK);
echo $numeric; // 1234

For your example "ABC-00000016081" you might use a regex that would match the first part up until you encounter not a zero and then use \\K to not include the previously consumed characters in the final match.

[^-]+-0+\\K[1-9][0-9]+

  • [^-]+ Match not a - one or more times using a negated character class
  • - Match literally
  • 0+ Match one or more times a zero (If you want your match without leading zeroes you could use 0* )
  • \\K Resets the starting point of the reported match
  • [1-9][0-9]* Match your value starting with a digit 1 -9

Test

You can substr off the ABC part and multiply with 1 to make it a number.

$ID = "ABC-000000160810";

Echo substr($ID, 4)*1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM