Skip to content
PHP Logo

How does the use of \d differ from [0-9] in regular expressions in PHP, and when should each be used?

In regular expressions in PHP, \d matches any digit character, equivalent to [0-9]. The main difference is that \d is a shorthand for matching any digit, while [0-9] explicitly specifies a range of characters from 0 to 9. Use \d when you specifically want to match any digit character, and use [0-9] when you want to match any character within the specified range of 0 to 9.

php
// Using \d to match any digit character
$pattern = '/\d/';
$string = '123abc';
if (preg_match($pattern, $string)) {
    echo 'Match found using \d';
}

// Using [0-9] to match any character in the range of 0 to 9
$pattern = '/[0-9]/';
$string = '123abc';
if (preg_match($pattern, $string)) {
    echo 'Match found using [0-9]';
}