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

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.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.