3

I've notice when the replacement has \ then the function will not work as expected. So I should escape backslash.

What other character should be escaped? I didn't succeed to find any documentation.

I can't use preg_quote() because it's used for escaping the pattern and not the replacement.

EDIT AGAIN: here is an example with single quote which show how the backslash cause problem:

 $replacement = '<head>content \0020 content</head>';
$subject = "<head>any header </head>";
$html_text = preg_replace ( "%<head>.*?</head>%s", $replacement, $subject, - 1, $count );
die ( $html_text );$subject, - 1, $count );
echo $html_text;

the above example should print : <head>content \0020 content</head>. but it's print <head>content <head>any header </head>20 content</head>

david
  • 3,310
  • 7
  • 36
  • 59

3 Answers3

0

\002 is an octal number that when rendered on a windows terminal displays a little smiley ☻ and then the trailing 0 from \0020. When viewed in a browser you just see the trailing 0. See Double quoted strings for the escape sequences. To use double quoted you would need to use this \\\\0020.

You can also use Single quoted strings or Nowdoc.

If you are reading this string from elsewhere you can use addslashes().

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • thank you for your answer, but actually i am reading the input from a post body, so i can't add single quote manually, how to change var string to be as single quoted ? – david Dec 03 '15 at 22:11
  • Edited, use addslashes(). – AbraCadaver Dec 03 '15 at 22:16
  • addslashes escape also ' & " , although there is no need to escape these character. how could i escape just the backslash ? thanks – david Dec 03 '15 at 22:36
  • abraCadaver , it seems that also with single quoted backslashs cause a problem, and they should be escaped , right ? i edit the question. – david Dec 04 '15 at 06:23
-1

The following should be escaped if you are trying to match a character

\ ^ . $ | ( ) [ ]     * + ? { } ,
thepiyush13
  • 1,321
  • 1
  • 8
  • 9
-1

The documentation you're looking for is here: Meta-characters. These are the special characters that you can use in a regex, which means if you need to literally search for them, you'll need to escape them.

haz
  • 1,549
  • 15
  • 20
  • And that is for the pattern not replacement. – AbraCadaver Dec 03 '15 at 21:43
  • Of course. Nothing needs to be escaped in the regex in the replace string, only the search string. – haz Dec 03 '15 at 22:54
  • You might need to escape your PHP string, depending on whether you're single-quoting or double-quoting, but the regex replace string is literal. – haz Dec 03 '15 at 22:54