8

I have to convert an ereg_replace to preg_replace

The ereg_replace code is:

ereg_replace( '\$([0-9])', '$\1', $value );

As preg is denoted by a start and end backslash I assume the conversion is:

preg_replace( '\\$([0-9])\', '$\1', $value );

As I don't have a good knowledge of regex I'm not sure if the above is the correct method to use?

Marcus
  • 822
  • 1
  • 8
  • 27
user1334167
  • 81
  • 1
  • 1
  • 3

2 Answers2

15

One of the differences between ereg_replace() and preg_replace() is that the pattern must be enclosed by delimiters: delimiter + pattern + delimiter. As stated in the documentation, a delimiter can be any non-alphanumeric, non-backslash, non-whitespace character. This means that valid delimiters are: /, #, ~, +, %, @, ! and <>, with the first two being most often used (but this is just my guess).

If your ereg_replace() worked as you expected, then simply add delimiters to the pattern and it will do the thing. All examples below will work:

preg_replace('/\$([0-9])/', '&#36;\1', $value);

or

preg_replace('#\$([0-9])#', '&#36;\1', $value);

or

preg_replace('%\$([0-9])%', '&#36;\1', $value);
Taz
  • 3,718
  • 2
  • 37
  • 59
  • Thank you so much for that - it's like getting more pieces to the puzzle as I'm upgrading from PHP 5.2.9 and noticed the DEPRECATED messages when using PHP 3 or above. – user1334167 Apr 15 '12 at 07:20
  • Thank you for the *clear*, and concise explanation. Not being an expert, they looked the same to me and only this answer explains the *actual* difference. (I realize this is nearly 10 years later `:)` ) – Scott Oct 01 '21 at 21:48
1

Try

preg_replace( '#\$([0-9])#', '\$$1', $value );
safarov
  • 7,793
  • 2
  • 36
  • 52