19

很抱歉提出问题,但在理解正则表达式代码时我毫无用处。

在我没有写的一个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所需的任何东西吗

4

4 回答 4

47

好问题 - 当您升级到 PHP 5.3 时需要这样做,其中eregeregi函数已被弃用。取代

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

采用

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

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

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

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

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

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

于 2012-03-31T07:54:24.490 回答
12

姑息 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); } }
于 2014-03-15T06:26:49.050 回答
1

您想要完全替代 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;
}
于 2012-03-31T08:00:11.247 回答
0

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了解更多信息 谢谢

:)

于 2012-03-31T07:51:18.907 回答