fish man
fish man

Reputation: 2710

Which symbols should be escaped with a backslash in php regex?

preg_match('@\.php@',$url,$match)

Common:-

any others?

Should @, ?, = be escaped?

Upvotes: 1

Views: 1327

Answers (3)

chrki
chrki

Reputation: 6333

There is a list of special Regex characters in the PHP documentation here: http://php.net/manual/en/function.preg-quote.php

The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

Upvotes: 5

user1726343
user1726343

Reputation:

@ and ? should be backslashified, = should not.

The characters you need to backslash escape in a regex include:

  • Square brackets []
  • Parentheses ()
  • Curly braces {}
  • Caret ^
  • Dollar sign $
  • Period .
  • Pipe |
  • Asterisk *
  • Plus +
  • Question mark ?
  • Backslashes \

Additionally, your regex delimiter, in this case @, needs to be backslashified.

It is important to note that certain characters may be metacharacters in a certain context. For example, the hyphen is not a metacharacter in the regex denoted by this string:

"/foo-/"

But is a metacharacter in the following string:

"/foo[a-z]/"

Upvotes: 2

Salman Arshad
Salman Arshad

Reputation: 272266

Perhaps you will find the preg_quote function useful:

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

Upvotes: 2

Related Questions