函数eregi()已弃用

时间:2011-04-18 09:18:43

标签: php regex preg-match eregi

不推荐使用函数eregi()。我怎样才能取代eregi()。我尝试使用preg_match然后停止工作。

我们帮助他们:

http://takien.com/513/how-to-fix-function-eregi-is-deprecated-in-php-5-3-0.php

之前的代码:

if ( ! eregi("convert$", $this->library_path))
        {
            if ( ! eregi("/$", $this->library_path)) $this->library_path .= "/";

            $this->library_path .= 'convert';
        }

if (eregi("gd2$", $protocol))
        {
            $protocol = 'image_process_gd';
        }

CODE THEN:

if ( ! preg_match("convert$/i", $this->library_path))
        {
            if ( ! preg_match("/$/i", $this->library_path)) $this->library_path .= "/";

            $this->library_path .= 'convert';
        }

if (preg_match("gd2$/i", $protocol))
        {
            $protocol = 'image_process_gd';
        }

3 个答案:

答案 0 :(得分:8)

preg_match期望它的正则表达式参数在一对分隔符内。

所以试试:

if ( ! preg_match("#convert$#i", $this->library_path)) {
        if ( ! preg_match("#/$#i", $this->library_path)) 
                $this->library_path .= "/";

        $this->library_path .= 'convert';
}

if (preg_match("#gd2$#i", $protocol)) {                                         
        $protocol = 'image_process_gd'; 
}     

答案 1 :(得分:2)

好像你刚忘了Delimiter

preg_match("~/$~", $this->library_path)

preg_match("~gd2$~i", $protocol)

但是在这两种情况下你都应该考虑不使用正则表达式,因为它们在这里超大了

$this->library_path[strlen($this->library_path) - 1] == '/'
substr($protocol, -3) == 'gd2'

答案 2 :(得分:1)

如果您只是检查另一个字符串是否存在,则应该使用strpos()函数。例如:

if(strpos('convert', $this->library_path) !== false) {
    // code here
}

更新:误读您要在字符串的END处检查它,使用substr()时,如果没有正则表达式,这仍然是可能的:

if(substr($this->library_path, -7) == 'convert'  {
    //code here
}

其中7是转换的长度,您可以使用strlen并从0中减去它以动态获取此数字。 这不会启动任何正则表达式,因此效率更高。