gpt4 book ai didi

php - 需要正则表达式来匹配包含 "http://"并以数组中的文件扩展名结尾的字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:35:14 26 4
gpt4 key购买 nike

正在寻找将找到匹配以下表达式的 php 解决方案:

  1. URL 包含“http://”(不一定以 http://开头)并且
  2. URL 以数组中的文件扩展名结尾。

文件扩展名数组示例

$filetypes = array(
jpg,
gif,
png,
js,
tif,
pdf,
doc,
xls,
xlsx,
etc);

这是我希望根据上述要求更新的工作代码:

现在,此代码有效并仅返回包含“http://”的 URL,但我还想包括第二个要求。

$i = 0;
$matches = false;
foreach($all_urls as $index => $value) {
if (preg_match('/http:/', $value)) {
$i++;
echo "[{$i}] {$value}<br>";
$matches = true;
}
}

最佳答案

你可以做一个 in_array()在你用 pathinfo() 检查的地方调用你的 if 语句如果扩展名在 $filetypes 数组中。

$i = 0;
$matches = false;
foreach($all_urls as $index => $value) {
if (preg_match('/http:/', $value) && in_array(pathinfo($value, PATHINFO_EXTENSION ), $filetypes)) {
$i++;
echo "[{$i}] {$value}<br>";
$matches = true;
}
}

编辑:

正如您在 comments 中所说一些网址包含单引号,您可以使用它来摆脱它们作为 @Ghost在评论中显示:

trim($value, "'")

然后在 in_array() 调用中使用它,如下所示:

in_array(pathinfo(trim($value, "'"), PATHINFO_EXTENSION ), $filetypes)
//^^^^^^^^^^^^^^^^^

关于php - 需要正则表达式来匹配包含 "http://"并以数组中的文件扩展名结尾的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30002760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com