ereg_replace to preg_replace

Hi. I’m sure this must have been covered somewhere but I searched and found some great answers, but not to my question.
Some years ago I built a site using a Sitepoint book as guidance and used the following;
$detail = ereg_replace(
‘\[L=([&-./a-zA-Z0-9|!%#?+,\‘=:~]+)]’.
'([&-
./a-zA-Z0-9|!%#?+$,\’“=:;~]+)\[EL]',
'<a href=”\\1">\\2</a>',$detail);

Now I need to upgrade to using preg_replace but I just can’t find where to place the delimiter. I seem to have tried just about every combination but still I get an error message.
Please can someone tell me where to put the delimiter(s) to make this work with preg_replace as well as it does with ereg_replace.

Thanks in advance.

John.

Excellent, thanks. it was the fact that the delimiter was also in the pattern that was confusing me but now it works a treat.

Thanks for your help guys, I used Salathe’s fix as it was simpler in this case.

John.

The pattern delimiters surround the regular expression, and any modifiers (which affect how the regex behaves) come after the ending delimiter.

[font=monospace]
|-------------- <pattern> -------------|
<delimiter><regex><delimiter><modifiers>

/color=#99CC33{2,4}[/color]/i
[/font]

The issue, in your case, is likely to be that your regex contains your desired delimiter (forward slash). Say you wanted to match “foo/bar”, the pattern /foo/bar/ would be properly interpreted as /foo/<ERROR: Unknown modifier ‘b’>.

Now, to get around that we can do one of two things:

  • Escape the delimiter within the pattern so that it does not get mistaken for the ending delimiter:
    [indent]/foo\/bar/[/indent]
  • (Preferred) Change the delimiter character to something which is not in the regex (commonly ~ or #):
    [indent]~foo/bar~[/indent]

On to your POSIX (ereg) regex, currently it is all regex:

\!%#?+,'=:~]+)\[EL]

  • Step 1 is to wrap the regex in delimiters. The regex makes use of the forward slash, so it is not a very good idea to use that as the delimiters: lets use a character that does not appear within the regex, @. (Aside: the delimiter can be any non-alphanumeric, non-backslash, non-whitespace ASCII character.)

    [indent]@\!%#?+,'=:~]+)\[EL]@[/indent]
  • Step 2 is… well, for this pattern there is no step 2. All you need to do is wrap it in a string (careful with quotes!) and Bob’s your uncle.

For more details on the differences between POSIX (ereg) and PCRE (preg) regular expressions in PHP check out this handy page in the manual: Differences from POSIX regex [to PCRE regex].


$detail = preg_replace(
'[COLOR="Red"]/[/COLOR]\\[L=([&-_.[COLOR="Red"]\\[/COLOR]/a-zA-Z0-9|!%#?+,\\'=:~]+)]'.
'([&-_.[COLOR="Red"]\\[/COLOR]/a-zA-Z0-9|!%#?+$,\\'"=:;~]+)\\[EL][COLOR="Red"]/[/COLOR]',
'<a href="\\\\1">\\\\2</a>',$detail);

Add characters in red :slight_smile: