gpt4 book ai didi

php preg_match 查找 标签但不带 gif 扩展名

转载 作者:行者123 更新时间:2023-12-02 05:14:05 24 4
gpt4 key购买 nike

我知道如何在字符串中查找 img 标签,但我需要排除任何带有 gif 扩展名的 img 标签。我如何在我的 preg_match 中使用否定?我只需要第一个不包含 .gif 扩展名的图像标签。

我目前有这个:

  $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
$pattern = "/<img[^>]+\>/i";
preg_match($pattern, $text, $matches);
$text = $matches[0];

$text 会给我第一个标签,例如<img src="something.gif" border="0" />但是,我不想接受 .gif,所以如果第一个是 gif,它将跳过它并继续搜索其他。

请告诉我如何更改我的代码。

非常感谢!

最佳答案

不要那样做。尝试使用正则表达式解析 HTML 是一项注定要失败的任务,因为 HTML 的复杂性或需求的轻微增加都会使您的正则表达式变得难以置信的复杂。

最好的方法是使用专为该任务设计的工具:DOMDocument 类。

$dom = new DOMDocument;
$dom->loadHTML($text);

$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
if (!substr($image->getAttribute('src'), -4) === '.gif') {
break;
}
}

// $image is now the first image that didn't end with .gif

关于php preg_match 查找 <img> 标签但不带 gif 扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14932421/

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