#1
  1. No Profile Picture
    Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    May 2006
    Location
    I'm sneaking up behind you.
    Posts
    1,490
    Rep Power
    832

    Php, difference between \d and [\d]


    Hello,
    I have this regex to check for the existence of digits in a given string. It may or may not contain anything else, but is should have one or more digits.
    Here is the code
    php Code:
     if (preg_match('/\d+/', $val))
    	echo "$val contains digits\n";
    else
    	echo "$val does not contain digits\n";

    php Code:
     if (preg_match('/[\d]+/', $val))
    	echo "$val contains digits\n";
    else
    	echo "$val does not contain digits\n";


    Both code snippets give same results. So, what is the difference between \d and [\d].

    Thank you.
    Why do we always seek someone, something or some thought? Are we afraid of ourselves?
  2. #2
  3. kill 9, $$;
    Devshed Supreme Being (6500+ posts)

    Join Date
    Sep 2001
    Location
    Shanghai, An tSín
    Posts
    6,897
    Rep Power
    3887
    There's no difference. Using [ ... ] allows you to create a character class which will match any of the characters contained within it. So for example if you wanted to match 'a', 'b' or 'c', you'd do:
    Code:
    [abc]
    There are also pre-created character classes (\w for 'word characters', \d for digits, etc). So these two are equivalent:
    Code:
    [0123456789]
    \d
    Your square bracket character classes can contain these predefined ones too, so if for example you wanted to match numeric digits or whitespace, you could do:
    Code:
    [\d\s]
    Here, because you're only using one predefined character class, the square brackets are unnecessary.

    Comments on this post

    • srisa agrees : Thank you.
    • ManiacDan agrees
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    May 2006
    Location
    I'm sneaking up behind you.
    Posts
    1,490
    Rep Power
    832
    Thanks.
    Some notes for you:
    I repped you but the message is not visible. When I tried to rep you again it said, 'You cannot rep the same post twice'.
    It would be better if the resources and suggestions threads are stickied. Otherwise they will be go into the last page.
    Why do we always seek someone, something or some thought? Are we afraid of ourselves?

IMN logo majestic logo threadwatch logo seochat tools logo