ereg_replace to preg_replace?

自古美人都是妖i 提交于 2019-12-18 04:08:41

问题


How can I convert

ereg_replace(".*\.(.*)$","\\1",$imgfile);

to

preg_replace... ?

?

I'm having trouble with it?


回答1:


preg_replace("/.*\.(.*)$/", "\\1", "foo.jpg")

I don't know why PHP requires the / delimiters. The only reason Perl, JS, etc. have them is that they allow regex literals, which PHP doesn't.




回答2:


You should know 4 main things to port ereg patterns to preg:

  1. Add delimiters(/): 'pattern' => '/pattern/'

  2. Escape delimiter if it is a part of the pattern: 'patt/ern' => '/patt\/ern/'
    Achieve it programmatically in following way:
    $ereg_pattern = '<div>.+</div>';
    $preg_pattern = '/' .addcslashes($ereg_pattern, '/') . '/';

  3. eregi(case-insensitive matching): 'pattern' => '/pattern/i' So, if you are using eregi function for case insenstive matching, just add 'i' in the end of new pattern('/pattern/').

  4. ASCII values: In ereg, if you use number in the pattern, it is assumed that you are referring to the ASCII of a character. But in preg, number is not treated as ASCII value. So, if your pattern contain ASCII value in the ereg expression(for example: new line, tabs etc) then convert it to hexadecimal and prefix it with \x.
    Example: 9(tab) becomes \x9 or alternatively use \t.

Hope this will help.




回答3:


delimiters, add any char to beginning and end of expression, in this case, and by tradition, the '/' character preg_replace('/.*\.(.*)$/',"\\1",$imgfile); The regex isn't very good, better to use strrpos and take substr().

Regex is slow, use this. $extension=substr($imgName,strrpos($imgName,'.'));



来源:https://stackoverflow.com/questions/2443895/ereg-replace-to-preg-replace

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