Really simple question: how can I preg_replace the backslash character?
7 Answers
Yes, but you need to escape it. When using it in the regexp use \\ to use it in the replacement, use \\\\ (that will turn into \\ that will be interpreted as a single backslash).
2 Comments
Elia Weiss
$htmlRes = preg_replace("~\\~", "", $htmlRes); Warning: preg_replace(): No ending delimiter '~' found
Johnco
That should be
$htmlRes = preg_replace("~\\\\~", "", $htmlRes);. When PHP parses the string, the escape sequences are processed, and it's interpreted as "~\\~", which is then parsed by the regexp engine, as a single back slash.You need to escape the backslash: \\
From the manual on preg_replace:
To use backslash in replacement, it must be doubled (
"\\\\"PHP string).
Alternatively, use preg_quote to prepare a string for a preg_* operation.
7 Comments
Pekka
@ajk are you using single quotes or double quotes?
Adam Grant
$the_name = preg_replace('\\\\', 'u', $the_name);
Pekka
@aj in that case, I think using only two backslashes should work. Single-quoted and double-quoted strings have different escaping rules
Adam Grant
Just looking to replace the backslash with nothing ("Susan\'s" -> "Susan's")
Adam Grant
Yeah, I tried that too and it didn't work. In both cases, it ends up returning an empty string.
|