脚本工作正常,但导致未定义的变量错误


Script is working but causing undefined variable error

使用此 sctip 清理我的文本文件:

$list = file_get_contents('file.txt');
$res = preg_match_all("/'d+'.'d+'.'d+'.'d+':'d+/", $list, $match);
if($res) {
    foreach($match[0] as $value)
    $listValue .= $value."'n";
    file_put_contents('file.txt', trim($listValue));
}

它正在工作,但我在日志中收到此错误消息:

 Notice: Undefined variable: listValue in /home/local/public_html/scripts/extractor.php on line 22

有什么想法吗?

在执行串联操作之前,您需要初始化变量$listValue

串联操作.=等于$listValue = $listValue.$anotherValue,所以如果你不初始化它,php显然会给你未定义的变量错误;

$list = file_get_contents('file.txt');
$res = preg_match_all("/'d+'.'d+'.'d+'.'d+':'d+/", $list, $match);
$listValue = "";
if($res) {
    foreach($match[0] as $value){
       $listValue .= $value."'n";
    }
    file_put_contents('file.txt', trim($listValue));
}