#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2004
    Posts
    13
    Rep Power
    0

    Simple Regex Query ?


    I am using the following expression on a PHP form:

    $pattern = '/[^0-9]/';

    I've very new to Regex, and although I understand the 0-9 part, I'm not sure what the ^ symbol is for.

    I'm also wanting to allow the option of a plus character at the start of the entry.

    Do I just add a plus, eg:

    $pattern = '/[^+0-9]/';

    I know this is going to be a straight forward questions for most of you, but I would appreciate your help.

    Thanks
    Daniel
  2. #2
  3. kill 9, $$;
    Devshed Supreme Being (6500+ posts)

    Join Date
    Sep 2001
    Location
    Shanghai, An tSín
    Posts
    6,897
    Rep Power
    3886
    Those square brackets create a character class, meaning that the expression will match any of the characters in the class, so [abc] would match an 'a' character or a 'b' character or a 'c' character.

    In some cases, you can use shortcuts to create ranges, such as [0-9], which is a character class that will match any of 0, 1, 2, 3, 4, 5, 6, 7, 8 or 9

    The caret at the start negates the character class, so [^0-9] will match any character that is NOT 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

    How you would go about adding the extra plus sign at the start depends on how the existing regexp is being used. Is it to validate phone numbers, by any chance? If so, it's probably being used negatively (i.e., if the pattern matches, show an error, since the string contains non-numeric characters).
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2004
    Posts
    13
    Rep Power
    0
    It is used to strip out characters that aren't 0-9 (and hopefully +).

    $pattern = '/[^0-9]/';

    $HTTP_POST_VARS['number_entered'] = preg_replace($pattern, '', $HTTP_POST_VARS['number_entered']);

    Thanks
    Daniel
  6. #4
  7. kill 9, $$;
    Devshed Supreme Being (6500+ posts)

    Join Date
    Sep 2001
    Location
    Shanghai, An tSín
    Posts
    6,897
    Rep Power
    3886
    There are probably better solutions, but this works:
    Code:
    $pattern = '/[^+0-9]|(?<!^)\+/';
    i.e. replace anything that isn't either numeric or a '+' character, or any '+' characters that are not at the beginning of the string.

    Comments on this post

    • prometheuzz agrees
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2004
    Posts
    13
    Rep Power
    0
    Thanks - I'll give this a try.

    Daniel

IMN logo majestic logo threadwatch logo seochat tools logo