检查是否存在以给定字符串开头的文件

Šim*_*das 2 php apache file exists

给出一个名字

$path = 'articles/001.html';
Run Code Online (Sandbox Code Playgroud)

我可以检查这样的文件是否存在如下:

if ( file_exists( $path ) ) {
    // include it
} else {
    // redirect to articles index
}
Run Code Online (Sandbox Code Playgroud)

但是,我正在考虑通过向其添加文章的标题来修改文章的URL.因此,如果用户请求此URL:

"http://foo.com/articles/001"
Run Code Online (Sandbox Code Playgroud)

我想将URL转换为:

"http://foo.com/articles/001/the-title-of-the-article-here"
Run Code Online (Sandbox Code Playgroud)

现在,这当然意味着我必须在某处存储该文章的标题(以及所有其他文章).标题位于<h1>文章的元素中,但我怀疑在服务器上阅读文章(文件)只是为了检索标题是个好主意.

所以,我正在考虑将标题放在文件名中,如下所示:

"001-the-title-of-the-article-here.html"
Run Code Online (Sandbox Code Playgroud)

然后我可以从文件名中提取它并将其添加到URL.但是,我不确定如何检查目录中是否存在这样的文件articles- 我得到的只是文章ID(001在本例中).

因此,基于ID,我想检查目录中是否存在articles以该ID开头的HTML页面,如果是,我想检索其文件名.

可以这样做吗?这是一个好方法吗?欢迎提出建议.

dec*_*eze 10

glob 可以根据您的模式匹配文件:

$files = glob('articles/001-*.html');
Run Code Online (Sandbox Code Playgroud)

它会为您提供所有匹配文件的数组.