How to Check if String Is an Octal Number in PHP?

Check if string is a valid octal value

In PHP, you can check if a string is an octal value or not, by using the following regular expression with preg_match():

function isOctal(string $str): bool {
    return preg_match('/^(?:0o|0)[0-7]{1,}$/i', $str);
}

var_dump(isOctal('030071')); // true
var_dump(isOctal('0o30071')); // true (PHP 8.1+)
var_dump(isOctal('0O30071')); // true (PHP 8.1+)

var_dump(isOctal('030088')); // false
var_dump(isOctal('123')); // false

The custom isOctal() function checks for numeric literals that start with a 0, 0o or 0O, followed by at least one number in the range of 0-7, and returns boolean true/false accordingly.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.