首页 > 解决方案 > 覆盖变量中的名称

问题描述

我有一个功能

public function saveImage(Request $request, $requestField, $path) {
        if ($request->hasFile($requestField)) {

            $image_path = public_path($this->{ $requestField });

            if (File::exists($image_path)) {
                File::delete($image_path);
            }

            $file = $request->file($requestField);
            $uploadname = $this->getUploadName($file);
            $pathFull = public_path($path);
            if (!File::exists($pathFull, 0775, true)) {
                File::makeDirectory($pathFull, 0775, true);
                }
            Image::make($file)->save($pathFull. $requestField. '-'. $uploadname);
            $this->{ $requestField } = $path. $requestField. '-'. $uploadname;

            return $file;
        }

        return false;
    }

接下来我调用这个函数

$file = $article->saveImage($request, 'image_detail', '/storage/article/' .$article->id. '/');

现在的问题是,我有一个$requestField,它现在具有价值'image_detail'

它应该在任何地方都有这个含义,除了这些行

$pathFull. $requestField. '-'. $uploadname
$path. $requestField. '-'. $uploadname

我希望将字段$requestField转换为这样的值'image-detail',即'_'用破折号替换下划线'-',是否可以在此函数中仅针对单独的行执行此操作?

标签: phplaravel

解决方案


Str::replace方法替换字符串中的给定字符串:

use Illuminate\Support\Str; 

$your_variable = 'image-detail';

$replaced = Str::replace('-', '_', $your_variable);

// image_detail

推荐阅读