1

This is what I'm trying to do,

   $line = "dsfsdf";
   if (!preg_match('/^(?=.{1,30}$)[a-zA-Z0-9\-\_]*$^/', $line))
   {
      echo 'No Match found';
   }
   else
   {
       echo 'Match found';
   }

The requirement is below,

  • it can have characters
  • it can have numbers
  • As special character, it can have only hyphen (-) and underscore (_) characters in it

I'm not so good at regex part. Can someone guide me how to achieve it with a simple explanation?

5
  • You must really remove ^ (start of string anchor) at the end. Try '/^[a-zA-Z0-9_-]{1,30}$/'. Or even '/^[\w-]{1,30}$/' Commented Aug 10, 2017 at 11:41
  • Thanks a lot.. it works like a charm. so, '\w-' includes all the alphanumeric character along with '-' and '_' ? Commented Aug 10, 2017 at 11:47
  • Yes, \w matches what [a-zA-Z0-9_] does if no u modifier is added. Please consider accepting my answer if it works for you. Commented Aug 10, 2017 at 12:36
  • one more thing, if there's one more condition that there should be white spaces then should i use '\s' ? Commented Aug 11, 2017 at 5:24
  • Yes, \s stands for whitespace. [\w\s-] will be the character class. Commented Aug 11, 2017 at 6:42

1 Answer 1

2

You must remove ^ (start of string anchor) at the end. Also, you may replace [a-zA-Z0-9_] with \w, as without any modifiers, they are equal.

The (?=.{1,30}$) lookahead makes the regex engine only match strings with 1 to 30 characters. You may remove the lookahead and just apply the limiting quantifier to your character class.

You may use

'/^[\w-]{1,30}$/'

If you prefer a more verbose way use

'/^[a-zA-Z0-9_-]{1,30}$/'

See the PHP demo.

Both mean:

  • ^ - start of string
  • [\w-]{1,30} - 1 to 30 letters/digits/underscores/- symbols
  • $ - end of string. NOTE that to match at the very end of the string, you need to use a D modifier, or replace $ with \z anchor (i.e. use '/^[\w-]{1,30}$/D' or '/^[\w-]{1,30}\z/' then).
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for clarifying that in a very simple way
@DebrajDas If you can have a \n at the end of the input and if you do not want to allow matching this string, use D modifier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.