22 Votes

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.

ReplyPositiveNegative
2Best Answer2 Votes

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.

$txt = "ABC...";

$reg = "...";
$reg = '#'.preg_quote($reg).'#';

$txt = preg_replace($reg, 'DEF', $txt);

echo $txt;  // ABCDEF

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

ReplyPositive Negative
Reply

Related Topics

Rename File to its Folder Name

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.