Jump to content

Only allowing numbers, letters, dashes, and underscores


LanceT

Recommended Posts

Insert Quote

What part of the expression allows the underscores and dash?

 

~^[-_a-z0-9]+$~im

 

[ ] denotes a character class

search google to learn about them

 

a-z, 0-9 are ranges

all other characters are taken as string literals

 

as you can see - and _ are the first two string literals in the char class

 

 

however in this pattern: ~[^-_a-z0-9]+~i

no part of it allows dashes or underscores the ^ symbol matches everything that is not what's in the char class

Link to comment
Share on other sites

From the docs:

 

By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless D modifier is set). This is the same as Perl.  When this modifier is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.

 

In this case, using /m could yield unwanted results for the poster. For example, "a\n-+$%^&#@" would be valid.

Link to comment
Share on other sites

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.