Laravel 在函数中遇到非数字值

Laravel A non-numeric value encountered on functions

代码出现以下错误的原因是什么? 第一次运行没有问题,但是第二次出现"A non-numeric value encountered"错误:

 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"

替换

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

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

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

这是因为此处串联优先:

'_'.$num-1

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

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