phpregexpreg-replaceereg

Replacing ereg_replace()


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?


Solution

  • 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:

    $row['subject'] = preg_replace('/\\\\/', '', $row['subject']);
    

    The regex is /\\/. Using a single backslash (\) produces an error; the backslash is an escape character in regex, 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 in PHP and 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:

    $row['subject'] = preg_replace('/[\]/', '', $row['subject']);
    

    A single backslash is enough. In the regex the 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 to ereg_replace(): do not use regex at all. Because all it does is to match (and replace) the backslashes, you don't need to use regex. A simple str_replace() is enough:

    $row['subject'] = str_replace('\\', '', $row['subject']);