drsc10888 2016-10-08 01:00
浏览 71
已采纳

文件名中的PHP变量

I did a quick Google search and didn't find anything on this so I'm not entirely sure if this is even possible.

Let's say I have a file with the name of img_type-grayscale_title-waterfall. Is it possible to use parts of the file name as variables?

Like: type-grayscale becoming in a php script $type = "grayscale" and title-waterfall becoming $title = "Waterfall".

Basically I'd like to store variables and values in a filename and extract them if possible.

I know I could use a database for this, but I have reasons for explicitly wanting to try something like this.

Ok so my mind completly drew a blank and I didn't even think about the fact that the file name is nothing more than a string.

With some reminders from some comments I remembered this small detail and came up with the following which works, but doesn't seem to be the best way to do so:

Code:

$data = "img_type-grayscale_title-waterfall";
list($fileType,$type, $title) = explode("_",$data);

list($type, $typeValue) = explode("-", $type);
list($title, $titleValue) = explode("-", $title);

echo "Type: " . $typeValue;
echo " ";
echo "Title: " . $titleValue;

Output:

Type: grayscale Title: waterfall

It just seems a bit excessive to have to add a new line like list($title, $titleValue) = explode("-", $title); for each variable.

  • 写回答

3条回答 默认 最新

  • doudou130216 2016-10-08 01:23
    关注

    I think I would do so with an associative array.

    <?php
    
    
    $filename = 'img_type-grayscale_title-waterfall';
    $result = Array();
    
    //let's parse the filename with _ as first level separator and - for second level
    
    $firstlevel = explode ('_', $filename);
    foreach ($firstlevel as $secondlevels) {
            $keyvalue = explode ('-', $secondlevels);
            //first the special case of the "img" first token which is the file type and has no value
            if (!isset($keyvalue[1])) { // there is for it a key but no value
                $result['filetype']=$keyvalue[0];
            }
            else {
                $result[$keyvalue[0]]=$keyvalue[1];
            }
    
    }
    
    echo $result['filetype']; //  "img"
    echo ' ; ';
    echo $result['type']; // "grayscale"
    echo ' ; ';
    echo $result['title']; // "waterfall"
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于github的项目怎么在pycharm上面运行
  • ¥15 内存地址视频流转RTMP
  • ¥100 有偿,谁有移远的EC200S固件和最新的Qflsh工具。
  • ¥15 找一个QT页面+目标识别(行人检测)的开源项目
  • ¥15 有没有整苹果智能分拣线上图像数据
  • ¥20 有没有人会这个东西的
  • ¥15 cfx考虑调整“enforce system memory limit”参数的设置
  • ¥30 航迹分离,航迹增强,误差分析
  • ¥15 Chrome Manifest扩展引用Ajax-hook库拦截请求失败
  • ¥15 用Ros中的Topic通讯方式控制小乌龟的速度,走矩形;编写订阅器代码