Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php regular expression backslash dash

Tags:

regex

php

I'm new in PHP and I'm trying to accommodate php regular expression

from w3schools this regular expression

"/([\w\-]+\@[\w\-]+\.[\w\-]+)/"

represents the e-mail regular expression, but I'm wondering what this class definition means "[\w\-]", \w any word character but what about "\-"?

(Edited)

like image 977
Aladdin Avatar asked Nov 30 '25 03:11

Aladdin


2 Answers

But what about \- ?

The hyphen is mostly a normal character in regular expressions.

  • Outside of a character class; it has no special meaning (do not need to escape the hyphen).
  • Inside of a character class it has special meaning.

You can place a hyphen as the first or last character of the class without escaping.

  • ( [-\w], [\w-] )

In some regular expression implementations, you can also place directly after a range without escaping.

  • ( [y-z-abc], [\w-abc] short-hand class )

Simply escaping the hyphen as the last character of the class is fine here.

[\w\-]  # any character of: word characters (a-z, A-Z, 0-9, _), 
        # match a literal hyphen `\-'
like image 161
hwnd Avatar answered Dec 02 '25 18:12

hwnd


[\w\-] means letters(capital and small letter both) and numbers including -(dash/hypen)

You may check your regex explanation here

[\w\-]+ match a single character present in the list below

Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]

\w match any word character [a-zA-Z0-9_]

\- matches the character - literally

like image 36
Rahul Tripathi Avatar answered Dec 02 '25 18:12

Rahul Tripathi