PHP: Escape or Mask RegEx-Characters in String
Question by Compi | Last update on 2021-04-02 | Created on 2016-09-27
I have an arbitrary string that I want to use within a regular expression. When testing some strings, I just covered that the expressions are only working properly when the string does not contain certain characters.
For example, it is not possible whenever the string contains a dot or a plus sign. However, when writing \. or \+ instead of the pure period or plus, again it works. I think you call this escaping or masking the corresponding characters.
But why is this so? And after all, which kind of characters have to be escaped at all? The longer I am working with regular expressions, the more characters I am encountering for which it seems to be necessary.
Related Topics
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
Rename File to its Folder Name
Tutorial | 0 Comments
PHP: Remove arbitrary Characters at the Beginning and the End of a String
Tutorial | 0 Comments
Textarea Maxlength: Limit Maximum Number of Characters in Textarea
Tutorial | 3 Comments
PHP Mail Function: UTF-8 E-Mail Headers
Info | 0 Comments
Create URL for Website from Title of Page
Tutorial | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
Some characters have a special meaning within regular expressions. For example, the dot is standing for an arbitrary character, the plus sign for a repetition. In order to be able to distinguish those special characters with special meaning from characters that should be threated as such character, you have to mark those cases. And this can be achieved with prepending of the \ character.
The characters with a special meaning within regular expressions are:
However, you do not have to write your own search and replace function for each of those characters. Instead, you can also just use the built in function preg_quote() provided by PHP, which takes away from you all of the work.
In this example, the dots alone would not work as a regular expression. Because of this, we are using preg_quote() and we get the desired result.
2016-09-28 at 18:31