Thread: Regex error

    #1
  1. No Profile Picture
    Banned
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Apr 2005
    Posts
    4,982
    Rep Power
    0

    Regex error


    Code:
    <?
    $address="5407 110th. St. SW";
    if (preg_match('/^[a-zA-Z0-9.,-\s]$/', $address)) {  
    	echo "Match";
    } 
    ?>
    I'm trying to match *only* a string of any length with letters, numbers, period, comma, dash, and space.

    I was hoping this example would match, but it does not. Why?

    I was thinking maybe I misunderstand ^ and $, so I tried this:

    '/[a-zA-Z0-9.,-\s]/'

    But it's no good.
    Last edited by Arty Ziff; September 6th, 2009 at 03:28 PM.
  2. #2
  3. No Profile Picture
    Banned
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Apr 2005
    Posts
    4,982
    Rep Power
    0
    OK, this seems to work:

    $pattern = '/^([a-zA-Z0-9\s.-])*$/';

    Is there anything obviously wrong wth it?
  4. #3
  5. No Profile Picture
    User 165270
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2005
    Posts
    497
    Rep Power
    938
    Originally Posted by Arty Ziff
    OK, this seems to work:

    $pattern = '/^([a-zA-Z0-9\s.-])*$/';

    Is there anything obviously wrong wth it?
    Looking at your previous post:

    Originally Posted by Arty Ziff
    a string of any length with letters, numbers, period, comma, dash, and space.
    you're missing the comma in your character class. Also note that you don't really need to group your character class (you can remove the parenthesis), and you must be aware that your current regex will also match an empty string. If you don't want to match an empty string, replace the STAR with a PLUS:

    PHP Code:
    $pattern  '/^[a-zA-Z0-9\s.,-]*$/';
    // or
    $pattern  '/^[a-zA-Z0-9\s.,-]+$/'
    A final remark: the '\s' will not only match white spaces, but also tabs and new lines.

IMN logo majestic logo threadwatch logo seochat tools logo