3

I have a folder that contains logos for sponsors. In my website, a user can belong to a sponsor and the sponsor_id is set in session when the user logs in.

Here is my code:

function sponsor_logos($sponsor_id) {
    $logos = glob("resources/content/sites/{$sponsor_id}*");

    foreach($logos as $logo) {
        if(file_exists("{$logo}"))
            echo "<img src='/{$logo}' />";
    }
}

The above works, but a sponsor can have multiple logos. So the multiple logos are saved like so: sponsor_id.jpg, sponsor_id_2.jpg, sponsor_id_3.jpg

I am not the strongest at regex, so any help is greatly appreciated! thanks!

4

2 回答 2

1

您最好打开目录并检查其中的所有文件(如果文件不多)。你可以这样做:

function sponsor_logos($sponsor_id) {
    if ($dh = opendir('resources/content/sites/')) {
        while (($file = readdir($dh)) !== false) {
            if(strpos($file, $sponsor_id . '.') === 0) {
                $sponsor_files[] = $file;
            }
            else if(strpos($file, $sponsor_id . '_') === 0) {
                $sponsor_files[] = $file;
            }
        }
        closedir($dh);
    }
    foreach($sponsor_files as $logo) {
        echo "<img src='resources/content/sites/" . $logo . "' />";
    }
}

但最好的解决方案是有正常的命名方案。

于 2012-07-04T14:12:54.247 回答
0

使用这个正则表达式sponsor_id(_\d+)?\.jpg

于 2012-07-04T13:29:57.957 回答