preg_match on a result of previous preg_match



我有这样的代码,它遍历一个字符串并输出img的第一个src=""属性。

我也需要去掉alt=""属性。

$first_image = '';
if ((preg_match('/<img[^>]*>/i', $article_fulltext, $matches ) == 1))
if (preg_match('/src="([^"]*)"/', $matches[0], $morematches ) == 1)
$first_image = $morematches[0];

我尝试过,但没有成功;

$first_image = '';
if ((preg_match('/<img[^>]*>/i', $article_fulltext, $matches ) == 1))
if (preg_match('/src="([^"]*)"/', $matches[0], $morematches ) == 1)
if (preg_match('/alt="([^"]*)"/', $matches[0], $morematchesAlt ) == 1)
$first_image = $morematches[0];
$first_image_alt = $morematchesAlt[0];

我做错了什么?

同意您宁愿使用DOMDocument的观点,但为了使用您的代码,您必须对其进行一点更改,如下所示:

<?php
$article_fulltext = '<html><body><img src="imgSrc" alt="imgAlt"></body></html>';
if (preg_match('/<img[^>]*>/i', $article_fulltext, $matches)) {
preg_match('/src="([^"]*)"/', $matches[0], $morematches);
preg_match('/alt="([^"]*)"/', $matches[0], $morematchesAlt);
$first_image = $morematches[0];
$first_image_alt = $morematchesAlt[0];
var_dump($first_image);
var_dump($first_image_alt);
}

当你运行这个脚本时,你会收到下一个结果:

string(12) "src="imgSrc""
string(12) "alt="imgAlt""

您的代码缺少正确定义条件语句结构的大括号。每当在if子句下使用多个语句时,建议使用大括号以防止它们嵌套并产生不希望的效果。

此外,正如已经提到的,正则表达式并不是解析HTML的最佳方式,因此这里有一个使用DOMDocument的解决方案:

<?php
# Create a new DOMDocument instance and load the html content.
$dom = new DOMDocument;
$dom -> loadHTML($article_fulltext);
# Cache the first image element.
$img = $dom -> getElementsByTagName("img") -> item(0);
# Print its 'src' and 'alt' attributes.
echo $img -> getAttribute("src");
echo $img -> getAttribute("alt");
?>

最新更新