需要一个PHP脚本诊断一小段代码

时间:2009-03-14 17:23:00

标签: php regex arrays

有人可以告诉我,我做错了吗?我很疯狂,下面的代码在localhost / WIN上运行得很完美,当我在webhost / linux上尝试它时会发出警告:

$lines = file('english.php');
foreach($lines as $line) {
    $matches=array();
    if (preg_match('/DEFINE\(\'(.*?)\',\s*\'(.*)\'\);/i', $line, $matches)) {
        $keys[] = $matches[1];
        $values[] = $matches[2];
    }
}
$lang = array_combine($keys, $values);

当我在webhost上测试时:

Warning: array_combine() expects parameter 1 to be array, null given in /home/xx/public_html/xx on line 616

但是在本地服务器(Windows XP)上,它的工作非常完美。我不知道我做错了什么,请帮我解决这个噩梦:(

感谢。

3 个答案:

答案 0 :(得分:2)

我没有看到你的代码有任何明显错误,但我很好奇为什么你要构建单独的数组然后组合它们而不是仅仅构建一个组合数组:

// Make sure this file is local to the system the script is running on.
// If it's a "url://" path, you can run into url_fopen problems.
$lines = file('english.php');

// No need to reinitialize each time.
$matches = array();

$lang = array();
foreach($lines as $line) {
    if (preg_match('/DEFINE\(\'([^\']*)\',\s*\'([^\\\\\']*(?:\\.[^\\\\\']*)*)\'\);/i', $line, $matches)) {
        $lang[$matches[1]] = $matches[2];
    }
}

(我也改变了你的正则表达式来处理单引号。)

答案 1 :(得分:0)

php版本是否相同?

您确定已将所有文件传输到虚拟主机吗?

答案 2 :(得分:0)

你的$ keys变量似乎是null,因为你没有在任何地方初始化它。

我最好的猜测是服务器上的english.php文件是空的(或者不存在),所以当你尝试读取它时,没有任何内容保存在$ keys变量中;

尝试在foreach语句之前添加该变量的初始值:

$lines = file('english.php');
$keys = array();
foreach($lines as $line) {
$matches=array();
    if (preg_match('/DEFINE\(\'(.*?)\',\s*\'(.*)\'\);/i', $line, $matches)) {
        $keys[] = $matches[1];
        $values[] = $matches[2];
    }
}
$lang = array_combine($keys, $values);

这样,即使文件不存在或为空,您也可以覆盖所有可能的路径。

你应该总是编码好像一切都可能出错,而不是相反:)

相关问题