gpt4 book ai didi

文件名中的 PHP 变量

转载 作者:行者123 更新时间:2023-12-03 23:49:24 24 4
gpt4 key购买 nike

我快速进行了 Google 搜索,但没有找到任何相关信息,所以我不确定这是否可行。

假设我有一个名称为 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;

输出:

类型:灰度标题:瀑布

必须为每个变量添加一个像 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"
?>

关于文件名中的 PHP 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39927634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com