I have some legacy code I'm trying to update to run on PHP 5.4:
$row['subject'] = ereg_replace('[\]', '', $row['subject']);
I know I have to replace this with preg_replace, but since I've never used ereg, I'm not sure what this actually does.
Is the equivalent:
preg_replace('/[\\]/'...
or
preg_replace('/\[\\\]/'...
Can anyone shine a light on what the correct replacement should be?
The code you posted replaces the backslashes with nothing and it doesn't match the square brackets; they are used to create a character range that contains only the backslash character and are completely useless on your
regex.The equivalent
preg_replace()statement is:The
regexis/\\/. Using a single backslash (\) produces an error; the backslash is an escape character inregex, it escapes the/making it be interpreted literally and not as the delimiter. The two extra backslashes are needed because the backslash is also an escape character inPHPand it needs to be escaped too.I guess this was the reason the original coder enclosed the backslash into a range, to circumvent the need for escaping and double escaping.
Using the same trick you can write it with
preg_replace()as:A single backslash is enough. In the
regexthe backslash escapes are not allowed in character ranges. And in PHP single-quoted strings, the backslash needs to be escaped only if it is the last character from the string.(I know, the documentation teaches us to double all the backslashes, but, on the other hand, it says that a backslash that does not precede an apostrophe or another backslash in single-quoted strings is interpreted literally.)
Back to the
regex, there is a better (faster, cleaner) way to rewrite the above call toereg_replace(): do not useregexat all. Because all it does is to match (and replace) the backslashes, you don't need to useregex. A simplestr_replace()is enough: