我有一个带有文件名的数组。
我想检查数组是否具有带有扩展名'.txt'的文件。
我该怎么做?
in_array
仅检查特定值。
尝试array_filter
。在回调中,检查.txt
扩展的存在。
如果array_filter
的结果有条目(真实),那么您可以获取第一个或全部。如果数组为空,则没有匹配。
您可以循环浏览数组中的项目,然后在每个项目上执行正则表达式或strpos匹配。找到比赛后,您可以返回true。
使用strpos()
:
$array = array('one.php', 'two.txt');
$match = false;
foreach ($array as $filename) {
if (strpos($filename, '.txt') !== FALSE) {
$match = true;
break;
}
}
带有正则:
$array = array('one.php', 'two.txt');
$match = false;
foreach ($array as $filename) {
if (preg_match('/.txt$/', $filename)) {
$match = true;
break;
}
}
两者都会导致$match
等于true
。
$files = array('foo.txt', 'bar.txt', 'nope.php', ...);
$txtFiles = array_filter($files, function ($item) {
return '.txt' === substr($item, -4); // assuming that your string ends with '.txt' otherwise you need something like strpos or preg_match
});
var_dump($txtFiles); // >> Array ( [0] => 'foo.txt', [1] => 'bar.txt' )
array_filter
函数通过数组循环,并将值传递到回调中。如果回调返回true,它将保留该值,否则它将从数组中删除值。在回调中传递所有项目后,返回结果数组。
哦,您只想知道.txt
是否在数组中。其他一些建议:
$match = false;
array_map(function ($item) use ($match) {
if ('.txt' === substr($match, -4)) {
$match = true;
}
}, $filesArray);
$match = false;
if (false === strpos(implode(' ', $filesArray), '.txt')) {
$match = true;
}
$iHaz = FALSE;
foreach ($arr as $item) {
if (preg_match('/.txt$/', $item)) {
$iHaz = TRUE;
break;
}
}
与建议array_filter
的其他答案相反,我不返回某些内容。我只是检查它是否存在于阵列中。此外,此实现比array_filter
更有效,因为它一旦找到东西就会突破循环。
由于您要处理文件,因此应该使用array_filter
和pathinfo
$files = array_filter(array("a.php","b.txt","z.ftxt"), function ($item) {
return pathinfo($item, PATHINFO_EXTENSION) === "txt";
});
var_dump($files); // b.txt
使用array_filter
的文件扩展程序过滤您的数组结果:
// Our array to be filtered
$files = array("puppies.txt", "kittens.pdf", "turtles.txt");
// array_filter takes an array, and a callable function
$result = array_filter($files, function ($value) {
// Function is called once per array value
// Return true to keep item, false to filter out of results
return preg_match("/.txt$/", $value);
});
// Output filtered values
var_dump($result);
导致以下结果:
array(2) {
[0]=> string(11) "puppies.txt"
[2]=> string(11) "turtles.txt"
}
执行它:http://goo.gl/f3ojr
如果您想要一个仅包含.txt
结束的字符串的过滤数组,则PHP8具有适合您的本机函数。
代码:(演示)
$array = ['one.php', 'two.txt'];
var_export(
array_filter(
$array,
fn($v) => str_ends_with($v, '.txt')
)
);
如果您想要一个true/false结果,并且不需要迭代整个数组,则有条件地 break
循环。(演示)
$found = false;
foreach ($array as $filename) {
if (str_ends_with($filename, '.txt')) {
$found = true;
break;
}
}
var_export($found);