When testing an answer for another user's question I found something I don't understand. The problem was to replace all literal \t
\n
\r
characters from a string with a single space.
Now, the first pattern I tried was:
/(?:\\[trn])+/
which surprisingly didn't work. I tried the same pattern in Perl and it worked fine. After some trial and error I found that PHP wants 3 or 4 backslashes for that pattern to match, as in:
/(?:\\\\[trn])+/
or
/(?:\\\[trn])+/
these patterns - to my surprise - both work. Why are these extra backslashes necessary?
The backslash character ( \ ) is the escaping character. It can be used to denote an escaped character, a string, literal, or one of the set of supported special characters. Use a double backslash ( \\ ) to denote an escaped string literal.
Escape Sequences In PHP, an escape sequence starts with a backslash \ . Escape sequences apply to double-quoted strings. A single-quoted string only uses the escape sequences for a single quote or a backslash.
\ The backslash suppresses the special meaning of the character it precedes, and turns it into an ordinary character. To insert a backslash into your regular expression pattern, use a double backslash ('\\'). ( ) The open parenthesis indicates a "subexpression", discussed below.
Checking information entered by users into a form is referred to as form validation. There are many different forms of validation, but the basic pattern match function in PHP is eregi , which stands for “evaluate regular expression, case insensitive”.
You need 4 backslashes to represent 1 in regex because:
"\\\\" -> \\
)\\ -> \
)From the PHP doc,
escaping any other character will result in the backslash being printed too1
Hence for \\\[
,
\
, one stay because \[
is invalid ("\\\[" -> \\[
)\\[ -> \[
)Yes it works, but not a good practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With