2

What is the reason for the following error in code? The first time runs without problems, But the second time "A non-numeric value encountered" error occurs:

 public function checkName(string $name, string $path, string $extension, int $num)
    {
        if (Storage::exists("$path/$name"))
        {
            $withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $name);

            if ($num > 1)
                $withoutExt = str_replace('_'.$num-1, '_'.$num, $withoutExt);
            else
                $withoutExt = $withoutExt . '_'.$num;

            $newName = "$withoutExt.$extension";

            if (Storage::exists("$path/$newName")) {
                return $this->checkName($newName, $path, $extension, $num+1);
            }
            else
                return $newName;
        }

        return $name;
    }

$fileNameSave = (new Attachment)->checkName($fileName, $filePath, $file->getClientOriginalExtension(), 1);

exception: "ErrorException"
line: 84
message: "A non-numeric value encountered"
4

2 回答 2

2

这是因为连接在这里优先:

'_'.$num-1

要解决此问题,只需将减法括在括号中:

str_replace('_'.($num-1), '_'.$num, $withoutExt);

于 2018-10-09T21:21:27.687 回答
0

代替

str_replace('_'.$num-1, '_'.$num, $withoutExt);

str_replace('_'.($num-1), '_'.$num, $withoutExt);

您的代码试图减去 _1 - 1,这就是错误所在。

于 2018-10-09T21:16:40.810 回答