php ereg_replace 到 preg_replace?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2443895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ereg_replace to preg_replace?
提问by sml
How can I convert
我该如何转换
ereg_replace(".*\.(.*)$","\1",$imgfile);
to
到
preg_replace... ?
?
?
I'm having trouble with it?
我有问题吗?
回答by Sumoanand
You should know 4 main things to port ereg patterns to preg:
您应该知道将 ereg 模式移植到 preg 的 4 个主要事项:
Add delimiters(/):
'pattern' => '/pattern/'Escape delimiterif 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, '/') . '/';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/').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.
添加分隔符(/):
'pattern' => '/pattern/'如果它是模式的一部分,则转义分隔符:
'patt/ern' => '/patt\/ern/'
通过以下方式以编程方式实现它:$ereg_pattern = '<div>.+</div>';$preg_pattern = '/' .addcslashes($ereg_pattern, '/') . '/';eregi(不区分大小写匹配):
'pattern' => '/pattern/i'因此,如果您使用 eregi 函数进行不区分大小写匹配,只需在新模式('/pattern/')的末尾添加 'i'。ASCII 值:在 ereg 中,如果您在模式中使用数字,则假定您指的是字符的 ASCII。但在 preg 中,数字不被视为 ASCII 值。因此,如果您的模式在 ereg 表达式中包含 ASCII 值(例如:换行、制表符等),则将其转换为十六进制并以 \x 为前缀。
Example: 9(tab) becomes \x9 or alternatively use \t.
Hope this will help.
希望这会有所帮助。
回答by Matthew Flaschen
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.
我不知道为什么 PHP 需要/分隔符。Perl、JS 等拥有它们的唯一原因是它们允许正则表达式文字,而 PHP 则不允许。
回答by Jimmy Ruska
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().
分隔符,在表达式的开头和结尾添加任何字符,在这种情况下,按照传统,'/' 字符preg_replace('/.*\.(.*)$/',"\\1",$imgfile);正则表达式不是很好,最好使用 strrpos 并采用 substr()。
Regex is slow, use this. $extension=substr($imgName,strrpos($imgName,'.'));
正则表达式很慢,使用这个。$extension=substr($imgName,strrpos($imgName,'.'));

