gpt4 book ai didi

php - 从 PHP 中的文本中提取图像源 - 需要 preg_match_all

转载 作者:行者123 更新时间:2023-12-02 07:11:58 25 4
gpt4 key购买 nike

我有一个小问题,因为我的 preg_match_all 没有正常运行。

我想做的是从 wordpress 的 post_content 中提取 所有图像 的 src 参数,这是一个字符串 - 而不是完整的 html 文档/DOM(因此不能使用文档解析器函数)

我目前正在使用下面的代码,不幸的是,它太乱了,只能用于 1 个图像 src,我想要来自该字符串的所有图像源

preg_match_all( '/src="([^"]*)"/', $search->post_content, $matches);

if ( isset( $matches ) )
{

foreach ($matches as $match)
{

if(strpos($match[0], "src")!==false)
{
$res = explode("\"", $match[0]);
echo $res[1];
}

}

}

有人可以帮忙吗...

最佳答案

使用正则表达式解析 HTML 文档非常容易出错。就像你的情况一样,不仅 IMG 元素有一个 SRC attribute (事实上​​,它甚至根本不需要是 HTML 属性)。除此之外,属性值也可能没有用双引号引起来。

最好使用像 PHP’s DOMDocument 这样的 HTML DOM 解析器及其方法:

$doc = new DOMDocument();
$doc->loadHTML($search->post_content);
foreach ($doc->getElementsByTagName('img') as $img) {
if ($img->hasAttribute('src')) {
echo $img->getAttribute('src');
}
}

关于php - 从 PHP 中的文本中提取图像源 - 需要 preg_match_all,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5102451/

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