Jump to content

Recommended Posts

Hey guys, I REALLY can't get my head around this RegEx shit.. not quite sure why though, anything I try doesn't work.. even with this simple regex i need.

 

Can anybody tell me the regex for any number, letter, period or underscore?

 

I think I'll be using eregi for it, unless you suggest something more efficient.

This is because i need to check a string to see whether it contains anything that is NOT this, then I can give the user an error.

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/203634-simple-regular-expression/
Share on other sites

Hey there.  If you want to check a string for a character which isn't a letter, number, period or underscore then you could use the following:

 

if (preg_match('/[^a-z0-9\._]/i', $yourstring) > 0) {
// contains bad characters
}

 

Basically the '^' character means find matches that aren't in the square brackets.  Then we're defining a range of all letters (a to z), all numbers (0 to 9), a period (which needs a backslash in front of it to escape it, since a period is a regex metacharacter) and an underscore.  The 'i' at the end of the regex, outside of the delimiters, means to make the search case-insensitive (so a-z also covers A-Z).

 

The reason I've used preg rather than ereg for this is that the ereg functions have been deprecated as of PHP 5.3, and will be removed from PHP 6, so using preg should extend the lifespan of your code somewhat.  :)

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.