5

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

我使用 ethis 帮助:

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';
        }

代码然后:

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';
        }
4

3 回答 3

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'; 
}     
于 2011-04-18T09:22:34.917 回答
2

看来您只是忘记了分隔符

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

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

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

$this->library_path[strlen($this->library_path) - 1] == '/'
substr($protocol, -3) == 'gd2'
于 2011-04-18T09:20:51.687 回答
1

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

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

更新:误读你想在字符串的末尾检查它,这仍然可以在没有正则表达式的情况下使用substr()

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

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

于 2011-04-18T09:39:02.487 回答