创建一个以'n'开头的所有jpeg文件的数组 - PHP

时间:2016-03-11 10:58:50

标签: php joomla

我想在目录中创建一个以字母'n'开头的所有文件的数组,并且是jpg或JP​​EG的图像文件。到目前为止我的代码是:

/**
 * Runs the provided raw resource as a script that doesn't return anything.
 * 
 * Warning: this is a NOT a foolproof SQL script interpreter.
 * 
 * Please note:
 * All terminators (;) must be at the end of a line.
 * 
 * 
 * @param db
 * @param rawResourceId
 */
public void runScript(SQLiteDatabase db, int rawResourceId, boolean okToFail)
{
    Log.i(getClass().getSimpleName(), "Running SQL script");
    InputStream in = context.getResources().openRawResource(rawResourceId);
    Scanner s = new Scanner(in);
    String sql = "";
    while (s.hasNext())
    {
        sql += " " + s.nextLine();
        if (sql.endsWith(";"))
        {
            try
            {
                db.execSQL(sql);
            }
            catch (SQLException e)
            {
                if (okToFail)
                    Log.w(getClass().getSimpleName(), e.getMessage());
                else
                    throw e;
            }
            sql = "";
        }
    }
    s.close();
}

我尝试在foreach中添加,但它导致500服务器错误。我是php的新手,所以任何建议都会非常感激。 此致

2 个答案:

答案 0 :(得分:2)

使用phps glob(),有关详细说明,请参阅http://php.net/manual/en/function.glob.php

// Make sure $uploads has a trailing /
if(substr($uploads, -1) != '/') $uploads .= '/';

// Find all jpg files whose where name starts with "n" regardless of jpg or JPG file extension (all cases are matched)
$images = glob($uploads . 'n*.[jJ][pP]{eg,g,Eg,eG,G}', GLOB_BRACE);

var_dump($images);

答案 1 :(得分:0)

编辑:重写,测试。无论你的文件是用小写还是大写命名,都可以正常工作。

请注意,您必须在结尾处设置带有斜杠的变量$uploads

$uploads = 'uploads/'; // must be with slash at the end

if ($dir = opendir($uploads))
{
  $images = array();

  foreach (glob($uploads."*.{jpg,jpeg,JPG,JPEG}", GLOB_BRACE) as $filename)
  {
    $f = str_replace($uploads, null, $filename);
    if (strtolower($f[0]) == 'n')
    {
      $images[] = $f;
    }
  }
}    

echo '<pre>';
print_r($images);
echo '</pre>';