
本文介绍了在 PHP 中判断文件名是否以特定字符串结尾的有效方法。针对 PHP 8 及以上版本,推荐使用内置函数 str_ends_with(),该函数简洁高效。对于 PHP 7,文章提供了多种模拟 str_ends_with() 功能的方案,并结合文件清理的实际场景,提供了完整的代码示例和注意事项,帮助开发者轻松实现文件管理功能。
PHP 8 引入了 str_ends_with() 函数,专门用于检查字符串是否以指定的后缀结尾。 这使得代码更加简洁易读。
<?php
$filename = 'sifriugh-80.json';
if (str_ends_with($filename, 'json')) {
echo "'$filename' 以 'json' 结尾。\n";
} else {
echo "'$filename' 不以 'json' 结尾。\n";
}
$filename = 'dlifjbhvzique-100.json';
if (str_ends_with($filename, '100.json')) {
echo "'$filename' 以 '100.json' 结尾。\n";
} else {
echo "'$filename' 不以 '100.json' 结尾。\n";
}
?>在文件清理脚本中的应用:
$fileSystemIterator = new FilesystemIterator('cache');
$now = time();
foreach ($fileSystemIterator as $file) {
$filename = $file->getFilename();
$filepath = 'cache/' . $filename;
if (str_ends_with($filename, '100.json')) {
// 每 7 天删除一次以 '-100.json' 结尾的文件
if ($now - $file->getCTime() >= 7 * 24 * 3600) {
unlink($filepath);
}
} else {
// 每 2 小时删除一次其他文件
if ($now - $file->getCTime() >= 2 * 3600) {
unlink($filepath);
}
}
}如果你的 PHP 版本低于 8,可以使用以下方法模拟 str_ends_with() 函数:
立即学习“PHP免费学习笔记(深入)”;
1. 使用 substr() 和 strcmp():
<?php
function str_ends_with(string $haystack, string $needle): bool
{
$length = strlen($needle);
if ($length === 0) {
return true;
}
return (substr($haystack, -$length) === $needle);
}
$filename = 'sifriugh-80.json';
if (str_ends_with($filename, 'json')) {
echo "'$filename' 以 'json' 结尾。\n";
} else {
echo "'$filename' 不以 'json' 结尾。\n";
}
?>2. 使用 preg_match():
虽然 str_ends_with() 更高效,但正则表达式也可以实现相同的功能。
<?php
$filename = 'sifriugh-80.json';
if (preg_match('/json$/', $filename)) {
echo "'$filename' 以 'json' 结尾。\n";
} else {
echo "'$filename' 不以 'json' 结尾。\n";
}
?>在文件清理脚本中的应用 (PHP 7 示例,使用 substr() 和 strcmp()):
<?php
function str_ends_with(string $haystack, string $needle): bool
{
$length = strlen($needle);
if ($length === 0) {
return true;
}
return (substr($haystack, -$length) === $needle);
}
$fileSystemIterator = new FilesystemIterator('cache');
$now = time();
foreach ($fileSystemIterator as $file) {
$filename = $file->getFilename();
$filepath = 'cache/' . $filename;
if (str_ends_with($filename, '100.json')) {
// 每 7 天删除一次以 '-100.json' 结尾的文件
if ($now - $file->getCTime() >= 7 * 24 * 3600) {
unlink($filepath);
}
} else {
// 每 2 小时删除一次其他文件
if ($now - $file->getCTime() >= 2 * 3600) {
unlink($filepath);
}
}
}
?>本文介绍了在 PHP 中判断字符串结尾的两种主要方法:使用 str_ends_with() (PHP 8+) 和使用替代方案 (PHP 7)。 选择哪种方法取决于你的 PHP 版本和项目需求。 对于 PHP 8+,str_ends_with() 是首选方案,因为它简洁高效。 对于 PHP 7,substr() 和 strcmp() 的组合是最佳选择。 无论你选择哪种方法,都应该注意文件路径、权限和错误处理,以确保代码的稳定性和可靠性。
以上就是PHP 中如何判断文件名是否以指定字符串结尾的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号