Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match with regex all special chars except "-" in PHP?

How can I match all the “special” chars (like +_*&^%$#@!~) except the char - in PHP?

I know that \W will match all the “special” chars including the -.

Any suggestions in consideration of Unicode letters?

like image 509
CaTz Avatar asked Mar 15 '12 19:03

CaTz


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What is the difference between () and [] in regex?

In other words, square brackets match exactly one character. (a-z0-9) will match two characters, the first is one of abcdefghijklmnopqrstuvwxyz , the second is one of 0123456789 , just as if the parenthesis weren't there. The () will allow you to read exactly which characters were matched.

What is the wildcard character in regular expressions that matches any character except newline?

The period ( . ) is a wildcard character in regular expressions. It will match any character except a newline ( \n ).


2 Answers

  • [^-] is not the special character you want
  • [\W] are all special characters as you know
  • [^\w] are all special characters as well - sounds fair?

So therefore [^\w-] is the combination of both: All "special" characters but without -.

like image 145
hakre Avatar answered Sep 28 '22 07:09

hakre


You can try this pattern

([^a-zA-Z-])

This should match all characters that are not a-z and the -

like image 45
Austin Brunkhorst Avatar answered Sep 28 '22 05:09

Austin Brunkhorst