ereg/eregi replacement for PHP 5.3


ereg/eregi replacement for PHP 5.3

很抱歉问了一个问题,但在理解regex代码时我毫无用处。

在我没有编写的php模块中,有以下函数

function isURL($url = NULL) {
    if($url==NULL) return false;
    $protocol = '(http://|https://)';
    $allowed = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)';
    $regex = "^". $protocol . // must include the protocol
                     '(' . $allowed . '{1,63}'.)+'. // 1 or several sub domains with a max of 63 chars
                     '[a-z]' . '{2,6}'; // followed by a TLD
    if(eregi($regex, $url)==true) return true;
    else return false;
}

有人能给我一个替换代码吗?用任何需要的东西来替换eregi

好问题-当您升级到PHP 5.3时需要这个问题,因为eregeregi函数已弃用。更换

eregi('pattern', $string, $matches) 

使用

preg_match('/pattern/i', $string, $matches)

(第一个参数中尾随的i表示忽略,对应于eregi中的i-在替换ereg调用的情况下跳过即可)。

但要注意新旧模式之间的差异!本页列出了主要差异,但对于更复杂的正则表达式,您必须更详细地查看POSIX regex(由旧的ereg/eregi/split函数等支持)和PCRE之间的差异。

但在您的示例中,您可以安全地将eregi调用替换为:

if (preg_match("%{$regex}%i", $url))
    return true;

(注意:%是一个分隔符;通常使用斜线/。您必须确保分隔符不在正则表达式中,或者对其进行转义。在您的示例中,斜线是$regex的一部分,因此使用不同的字符作为分隔符更方便。)

Paliative PHP 5.3,直到您替换所有不推荐使用的函数

if(!function_exists('ereg'))            { function ereg($pattern, $subject, &$matches = []) { return preg_match('/'.$pattern.'/', $subject, $matches); } }
if(!function_exists('eregi'))           { function eregi($pattern, $subject, &$matches = []) { return preg_match('/'.$pattern.'/i', $subject, $matches); } }
if(!function_exists('ereg_replace'))    { function ereg_replace($pattern, $replacement, $string) { return preg_replace('/'.$pattern.'/', $replacement, $string); } }
if(!function_exists('eregi_replace'))   { function eregi_replace($pattern, $replacement, $string) { return preg_replace('/'.$pattern.'/i', $replacement, $string); } }
if(!function_exists('split'))           { function split($pattern, $subject, $limit = -1) { return preg_split('/'.$pattern.'/', $subject, $limit); } }
if(!function_exists('spliti'))          { function spliti($pattern, $subject, $limit = -1) { return preg_split('/'.$pattern.'/i', $subject, $limit); } }

您想要完整替换preg_match和eregi吗?

if(!filter_var($URI, FILTER_VALIDATE_URL))
{ 
return false;
} else {
return true;
}

或电子邮件:

if(!filter_var($EMAIL, FILTER_VALIDATE_EMAIL))
{ 
return false;
} else {
return true;
}

eregi在PHP中折旧,您必须使用preg_match

function isValidURL($url)
{
    return preg_match('%^((https?://)|(www'.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i', $url);
}

if(isValidURL("http://google.com"))
{
    echo "Good URL" ;
}
else
{
    echo "Bad Url" ;
}

请参阅http://php.net/manual/en/function.preg-match.php了解更多信息感谢

:)