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(
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.
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.
The pattern delimiters surround the regular expression, and any modifiers (which affect how the regex behaves) come after the ending delimiter.
|-------------- <pattern> -------------|
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:
- (Preferred) Change the delimiter character to something which is not in the regex (commonly ~ or #):
On to your POSIX (ereg) regex, currently it is all regex:
- 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.)
- 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(
Add characters in red