Converting an ereg_replace to preg_replace

这一生的挚爱 提交于 2019-12-23 09:24:04

问题


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?


回答1:


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);



回答2:


Try

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


来源:https://stackoverflow.com/questions/10159990/converting-an-ereg-replace-to-preg-replace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!