phpbase36

How to confirm that a string is valid base36 of an integer?


I had code like this:

$alias = 'myalias';
echo "<pre>";
echo "
ALIAS: $alias
ROUND: ", intval($alias, 36) , "\n" ,
"AGAIN: ", base_convert(intval($alias, 36), 10, 36)
;

echo "<hr>";

$alias = '27xk3q';
echo "<pre>";
echo "
ALIAS: $alias
ROUND: ", intval($alias, 36) , "\n" ,
"AGAIN: ", base_convert(intval($alias, 36), 10, 36)
;

This used to work, and still does on my home Mac computer. The output is:

ALIAS: myalias
ROUND: 2147483647
**AGAIN: zik0zj**

ALIAS: 27xk3q
ROUND: 134255366
AGAIN: 27xk3q

But when I upload this to my Linux server, it echoes different things!

ALIAS: myalias
ROUND: 49962861028
**AGAIN: myalias**

ALIAS: 27xk3q
ROUND: 134255366
AGAIN: 27xk3q

As you see, the "myalias" string just prints as itself in the Linux version of PHP.

If this doesn't work or is wrong code, I need to know a foolproof way of checking whether a string is a valid base36 version of an integer or not.

Thanks!


Solution

  • As you see, the "myalias" string just prints as itself in the Linux version of PHP.

    And it is correct behaviour. You get another results on your mac - because it is 32bit and your number is truncated to 2147483647 (2^32 - 1)

    if (preg_match('~^[a-z\d]+$~', $string)) {
        // valid base36
    }