SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Addict
    Join Date
    May 2006
    Location
    Ljubljana
    Posts
    241
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    simple php regex question

    Hello

    I'd like to match the string field_id_{any number}

    Which would match:

    field_id_5
    field_id_300

    and wouldnt match anything that doesnt have number at the end or doesnt begin with 'field..' such as:

    ffield_id_5_
    etc..

    I just need to return true or false (if the string didnt match).

    Should I use ereg or any other php regex function?

    The code I have at the moment:

    Code:
    ereg('field_id_', "field_id_[0-9]");
    This wont work for all scenarios mentioned above.

    Many thanks in advance!

  2. #2
    SitePoint Enthusiast
    Join Date
    Jan 2008
    Posts
    86
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    function checkField($field) {
        return 
    preg_match("^field_id_([0-9]+)^i"$field);
    }

    if (
    checkField("field_id_300_")) echo "no";
    if (
    checkField("field_id_300")) echo "yes"
    You can use ereg, but that's how I would do it using preg.

  3. #3
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    if ( (bool)preg_match'/^field_.*?_\d+$/'$field ) === false )
        
    // not valid! 
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  4. #4
    SitePoint Addict
    Join Date
    May 2006
    Location
    Ljubljana
    Posts
    241
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for your help.

    I dont know why it will also return true for the following string(s):
    field_id_3d4
    field_id_34ff

    Any idea?

    Thanks again!

  5. #5
    SitePoint Addict
    Join Date
    May 2006
    Location
    Ljubljana
    Posts
    241
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by logic_earth View Post
    PHP Code:
    if ( (bool)preg_match'/^field_.*?_\d+$/'$field ) === false )
        
    // not valid! 
    This works as expected. Thank you very much!

  6. #6
    @php.net Salathe's Avatar
    Join Date
    Dec 2004
    Location
    Edinburgh
    Posts
    1,397
    Mentioned
    65 Post(s)
    Tagged
    0 Thread(s)
    Would the pattern /^field_id_\d+$/D not better suit your needs?
    Salathe
    Software Developer and PHP Manual Author.


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
  •