SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Thread: Regex

  1. #1
    SitePoint Addict
    Join Date
    Jul 2007
    Location
    San Jose, California
    Posts
    355
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Regex

    Hey,
    I'm a little new with regex as I always seem to be. My question in general is i want to do a string search based off a regular expression.
    So say I want to validate what is in a string, not match the string.

    Example:
    I want "foo bar" to return false but "foo.bar" to return true. My orginal attempt was something along the lines of
    PHP Code:
    preg_match("([A-Za-z.-_]+)""Foo Bar"
    This was stopping after it found Foo. I want to set it to check the entire string.

    I thought I should change teh regex to something like
    "^([A-Za-z.-_]+)$" But that was not working. COuld somebody help me.

  2. #2
    SitePoint Zealot shoorace's Avatar
    Join Date
    Jun 2005
    Location
    Florida
    Posts
    142
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try this:

    PHP Code:
    echo preg_match("(^[A-Za-z.-_]+$)""Foo Bar"$matches);
    print_r($matches);
    echo 
    preg_match("(^[A-Za-z.-_]+$)""Foo.Bar"$matches);
    print_r($matches); 

  3. #3
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    the preg_* functions use PCRE regex.
    You must use a delimiter with PCRE regex to seperate the actual expression from the optional flags. I used the D flag, otherwise it would allow the string to end in a newline character.

    PHP Code:
    echo preg_match("/^[A-Za-z.-_]+$/D""Foo Bar"$matches);
    print_r($matches); 
    http://www.regular-expressions.info/tutorial.html


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
  •