Question:

In PHP, how do I allow "." and "-" using preg_match?

by  |  earlier

0 LIKES UnLike

I am trying to write a preg_match expression that will allow "." or "-" along with any letters or numbers, but I can't figure out how to do it.

Here is what I have:

preg_match("/^_?\w $/", $userName)

Any suggestions?

Thanks!

 Tags:

   Report

1 ANSWERS


  1. dot and dash are special pattern modifiers but you can escape them using backslashes to use them in patterns.

    Here is the regexp you are asking for:

    preg_match('{^_?[a-z0-9_\\.\\- ]+$}i', $userName);

    Some explanation:

    * I used single quotes just cuz i prefer them (:

    * I used curly brackets to enclose the regexp... many characters can be used for this purpose including /

    * I used double back-slashes. Two \\ evaluates to one \ inside single quoted string and then when this goes to preg engine, it escapes the next character (dot and dash)

    * plus indicates one or more of the characters from the preceding group

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions