【问题标题】:PHP wildcard character in the string字符串中的 PHP 通配符
【发布时间】:2014-06-14 05:39:27
【问题描述】:

我正在呼应 div 的嵌入式样式。在那种风格中,我正在设置背景图像。我知道图像文件名,但我不能确定文件类型,因为它可以是 jpeg、jpg、gif 或 png。

就像在这个例子中一样,它可能是 png 图像。

if(file_exists("images/img_".$loggedInUser->user_id.".jpeg")){
  echo "style='background-image: url(\"images/img_".$loggedInUser->user_id.".jpeg\");'";
}

这里是否可以使用某种通配符进行扩展?

【问题讨论】:

  • 如果只有 4 种可能性,为什么不直接使用 if else 并列出所有 4 个选项?
  • 为什么不直接存储文件名?每次需要显示页面时开始猜测似乎毫无意义。

标签: php


【解决方案1】:

通配符可以与glob() 一起使用。

例子:

$pics = glob("images/img_" . $loggedInUser->user_id . ".*");
if (isset($pics[0])) {
    // file exists
}

fnmatch() 很有用。

另一种方式,使用有点像经理class

class Image {
    private $user;
    public function __construct($user) {
        $this->user = $user;
    }

    public function getPicture() {
        $path = glob("images/img_" . $this->user . ".*");
        if (isset($pics[0]) {
            return "style='background-image: url(" . $pics[0] . ");'";
        }
    }
}

用法:

$pic = new Image($loggedInUser->user_id);
echo $pic->getUserPicture();

【讨论】:

    【解决方案2】:

    如果多个文件与模式匹配,则将使用第一个:

    if($file = glob("images/img_{$loggedInUser->user_id}.*")) {
        echo "style='background-image: url(\"{$file[0]}\");'";
    }
    

    如果您想要多个文件的不同行为,请对其进行调整。

    【讨论】:

      猜你喜欢
      • 2011-09-04
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      相关资源
      最近更新 更多