PHP: Test strings for octal numbers
January 25th, 2009 by Elchie
Today I had to test if a string entered by the user is a octal number.
So first I remembered: PHP will detect octal numbers by a leading zero, if there is a non-octal digit within this number, all following digits will be removed from the converted number. So I tried:
$test = intval(’0′.$entered);
But the result wasn’t an octal - next idea: Use sprintf:
$test = sprintf(”%o”, ‘0′.$entered);
But with %o the number will be treated as decimal integer - so your number will be handled as decimal, that will result in a other octal number.
So finally I just test it now with a simple regular expression:
if(preg_match(’/[0-7]+/’, $entered)>0)
// is octal …
Seems to be the only way to detect octal numbers…
Posted in Uncategorized