Skip to content
Advertisement

Get value by sweeping PHP string

I have the following value in a variable:

JavaScript

obtained from:

JavaScript

I need to start sweeping from left to right and when I find the first non-zero number that from there saves the value in a variable, for example: M000000017590 = 17590 A str_replace does not help me and replacing the 0 with "" since inside the last string it can also contain 0, some help?

Advertisement

Answer

In PHP strings are byte arrays, you can leverage on that

JavaScript

You start reading chars from your string one-by-one and check whether its numeric value holds for you or not. So as soon as you find a desired value(non-zero in your case) you start accumulating from thereon until you encounter an undesired value (zero/alpha in your case)

UPDATE: As mentioned by @waterloomatt if there are zeros embedded inside a valid sequence then the above algorithm fails. To fix this try

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement