On Mar 16, 2013 6:14 AM, "Ashley Sheridan" <a...@ashleysheridan.co.uk> wrote:
> On Fri, 2013-03-15 at 22:32 -0400, Andrew Ballard wrote:
>> > Guess regex are the only useful solution here. When you consider to use
>> > built-in functions, just remember, that for example '0xAF' is an
>> > too, but '42.00' isn't.
>> Shoot...I hadn't considered how PHP might handle hex or octal strings
>> casting to int. (Again, not in front of a computer where I can test it
>> right now. )
>> Regexes have problems with more than 9 digits for 32-bit ints. I guess to
>> some degree it depends on how likely you are to experience values that
> Do they? Regex's deal with strings, so I don't see why they should have
such issues. I've certainly never come across that problem, or heard of it
Sure. If the string is nine or fewer digits, they can all be 0-9. If it is
10 digits, the first digit can only be 1-2. If it's 1, the remaining nine
digits can still be 0-9, but if the first digit is 2, the second digit can
only be 0-1. If the second digit is 0, the remaining eight digits can still
be 0-9, but if it is 1, the third digit can only be 0-4. If the third digit
is 0-3, the remaining seven digits can still be 0-9, but if it is 4, the
fourth digit can only be 0-7.
This pattern would continue for each of the remaining digits. Hopefully you
get the idea. When you get to the final digit, its range depends not only
on the nine preceding digits, but also the sign. If this is 64-bit, that
adds even more wrinkles (including being aware of whether your
implementation supports 64-bit ints). It may be possible to do with regular
expressions, but it would definitely be complex and probably a time sink.
As I said, if you KNOW you won't be dealing with integers that are more
than nine digits, the regex should work fine.
Remember, the OP didn't ask if it was an integer in the realm of infinite
pure integers; he asked how to tell if a string was a number that could be
converted to an int (presumably without loss).