SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Dec 2002
    Posts
    74
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Regular expression

    Hi!

    I want to check if a grade is on the right format. They can be from 1-6.
    ie, 1,0 and 5,1 but 6,1 is not

    I've tried with:
    PHP Code:
    $grade '1,9';
    if (
    eregi('[1-6]{1}[,][0-9]{1}'$grade)) {
      echo 
    'correct format';
    } else {
      echo 
    'incorrect format';

    This seems to work, except when I have 6,1 up to 6,9
    Any help is appreciated
    Einar

  2. #2
    SitePoint Wizard samsm's Avatar
    Join Date
    Nov 2001
    Location
    Atlanta, GA, USA
    Posts
    5,011
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    First off, ditch the ereg. :-)
    The preg functions are faster and more powerful.

    I think the best option in this circumstance would be an "or".
    preg_match('/^6,0|[1-5],[0-9]$/', $source);
    or, the same thing slightly shorter:
    preg_match('/^6,0|[1-5],\d$/', $source);

    Note that the comma does not need to be in a character class (brackets) and that I've included ^ (beginning of string) and $ (end of string) so that 16,03 doesn't match.

    Also, you might consider doing this numerically. Something like:
    PHP Code:
    $grade 4.9;
    if (
    $grade <= 6)
    {
        echo 
    'True!';
    }
    ?> 
    You would still need to deal with negative numbers and decimal places in the hundreds, but I bet that would be an overall faster approach.
    Using your unpaid time to add free content to SitePoint Pty Ltd's portfolio?

  3. #3
    SitePoint Enthusiast
    Join Date
    Dec 2002
    Posts
    74
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks samsm!
    This was what I'm looking for. Is it a noticeable speed difference between ereg and preg?

  4. #4
    SitePoint Wizard samsm's Avatar
    Join Date
    Nov 2001
    Location
    Atlanta, GA, USA
    Posts
    5,011
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by lavik
    Thanks samsm!
    This was what I'm looking for. Is it a noticeable speed difference between ereg and preg?
    I have not done benchmarks. People who have say that preg is often about twice as fast. It would depend upon the specific regular expression, however.

    In addition, the preg regular expressions hoave more features, so it is valuable to get used to those.
    Using your unpaid time to add free content to SitePoint Pty Ltd's portfolio?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •