文件名中的 PHP 变量


PHP Variables In File Name

我做了一个快速的谷歌搜索,没有找到任何关于这个的东西,所以我不完全确定这是否可能。

假设我有一个名为 img_type-grayscale_title-waterfall 的文件。是否可以使用部分文件名作为变量?

喜欢: type-grayscale成为 php 脚本$type = "grayscale"title-waterfall变得$title = "Waterfall"

基本上,我想将变量和值存储在文件名中,并在可能的情况下提取它们。

我知道我可以为此使用数据库,但我有理由明确想要尝试这样的事情。

好的,所以我的头脑完全空白,我什至没有想到文件名只不过是一个字符串的事实。

在一些评论中的一些提醒下,我想起了这个小细节,并提出了以下有效的方法,但似乎不是最好的方法:

法典:

$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;

输出:

Type: grayscale Title: waterfall

必须为每个变量添加一个像 list($title, $titleValue) = explode("-", $title); 这样的新行似乎有点过分。

我想我会用一个关联数组来做到这一点。

<?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"
?>

你可以尝试做:

function get_parts( $delimiters, $string ){
        return explode( chr( 1 ), str_replace( $delimiters, chr( 1 ), $string ) );
    }
    $string = 'img_type-grayscale_title-waterfall';
    $parts = get_parts( array('-', '_', '-' ), $string );

然后你会得到一个带有分割部分的数组。

Array ( 
   [0] => img 
   [1] => type 
   [2] => grayscale 
   [3] => title 
   [4] => waterfall 
);
$first = '$'.$parts[1].' = '.$parts['2'];
$second = '$'.$parts[3].' = '.$parts['4'];

结果是:

echo $first will print  $type = grayscale 
echo $second will print $title = whaterfall 
        $filename = 'img_type-grayscale_title-waterfall';
        $items = explode('_', $filename);
        $vars = explode('-', $items[1]);
        $name = $vars[0];
        $$name = $vars[1];
        echo $type;
        $vars1 = explode('-', $items[2]);
        $name1 = $vars1[0];
        $$name1 = $vars1[1];
        echo $title;