Need help with some regular expressions in PHP
I need to port some simple eregi regular expressions to preg_match for PHP 5.3/6.0 compilance.
Since I'm not too confident in my regular expression porting skills I need some help...
#1
Old version:
if( eregi('foo',$myVar) ) {
$aresult = explode('/',stristr($myVar,'foo'));
$aversion = explode(' ',$aresult[1]);
}
New version:
if( preg_match('/Foo\/([^ ]*)/i',$myVar,$matches) ) {
$aversion = $matches[1];
}
#2
Old version:
if( eregi('bar',$myVar) && ! eregi('rv:[0-9]\.[0-9]\.[0-9]',$myVar)) {
$aresult = explode('/',stristr($myVar,'bar'));
$aversion = explode(' ',$aresult[1]);
}
开发者_开发知识库
New version:
//Not done yet need help
Your second snippet is pretty much the same as the first, just with that extra condition. I'm going to guess that your actual code (or how you want it to work) is a little different to that presented? If so, could you elaborate on those differences please?
Either way, your #2 could look similar to #1.
if (preg_match('~bar/([^ ]*)~i', $myVar, $match) && ! preg_match('/rv:[0-9]\.[0-9]\.[0-9]/', $myVar)) {
$aversion = $match[1];
}
The use of ~
as the delimiters might seem strange; the reasoning being that the regular expression contains the most usual delimiting character (/
) so an alternative is used instead of escaping the slash as you did in the question.
精彩评论