#1
  1. No Profile Picture
    Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    May 2006
    Location
    I'm sneaking up behind you.
    Posts
    1,490
    Rep Power
    832

    Allow only alphanumeric characters, white spaces and hyphen.


    Hello,

    I have come up with this regex for making sure that given string contains only alphanumeric characters or spaces or a hyphen.
    php Code:
     
    $val = $argv[1];
    $reg = "#[^a-z0-9\s-]#i";
    $count = preg_match($reg, $val, $matches);
    if ($count > 0){
    	echo "$val contains invalid characters\n";
    	print_r($matches);
    }
    else{
    	echo "$val DOES NOT contain invalid characters\n";
    	echo "count is $count";
    }

    I have tested and it seems okay. I am not well versed with regex, so came here for a confirmation.
    If you didn't already know, it is in PHP PCRE.

    Thank you.
    Why do we always seek someone, something or some thought? Are we afraid of ourselves?
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,965
    Rep Power
    9397
    Looks good.

    Remember that "\s" includes \n(ewline) \r(eturn) \t(tab) \v(ertical tab) \f(orm feed) and space.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    May 2006
    Location
    I'm sneaking up behind you.
    Posts
    1,490
    Rep Power
    832
    Thank you. Is there an expression to allow only space and deny newlines, tabs etc?
    Why do we always seek someone, something or some thought? Are we afraid of ourselves?
  6. #4
  7. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,965
    Rep Power
    9397
    Besides the "expression" you get when you press the spacebar on your keyboard?
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    May 2006
    Location
    I'm sneaking up behind you.
    Posts
    1,490
    Rep Power
    832
    I'm not sure i followed you. I will try to make myself clearer. In terms of keyboard, only alphabets, numbers, hypen and space bar are to be allowed.
    Why do we always seek someone, something or some thought? Are we afraid of ourselves?
  10. #6
  11. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,965
    Rep Power
    9397
    Since \s included any kind of whitespace, your question was what can be used to only represent a space.
    And I'm telling you, a space will represent a space.
    Code:
    #[^a-z0-9 -]#i

    Comments on this post

    • srisa agrees : My 2 cents in getting you those blue/purple squares.

IMN logo majestic logo threadwatch logo seochat tools logo