使用正则表达式从字符串中删除除图像标签以外的所有内容

Remove everything except image tag from string using regular expression

我有包含所有 html 元素的字符串,我必须删除除图像之外的所有内容。

目前我正在使用这个代码

$e->outertext = "<p class='images'>".str_replace(' ', ' ', str_replace('Â','',preg_replace('/#.*?(<img.+?>).*?#is', '',$e)))."</p>";

它符合我的目的,但执行速度很慢。做同样的任何其他方式将是可观的。

您提供的代码似乎无法正常工作,甚至正则表达式也有问题。您应该像这样删除初始斜杠 /#.*?(<img.+?>).*?#is.

您的想法是删除所有内容并只留下图像标签,这不是一个好方法。更好的方法是考虑只捕获所有图像标签,然后使用匹配项构建输出。首先让我们捕获图像标签。这可以使用这个正则表达式来完成:

/<img.*>/Ug

U 标志使正则表达式引擎变得懒惰而不是急切,因此它将匹配它找到的第一个 > 的遇到。

DEMO1

现在为了构造输出,让我们使用方法 preg_match_all 并将结果放入字符串中。这可以使用以下代码完成:

<?php
// defining the input
$e = 
'<div class="topbar-links"><div class="gravatar-wrapper-24">
<img src="https://www.gravatar.com/avatar" alt="" width="24" height="24"     class="avatar-me js-avatar-me">
</div>
</div> <img test2> <img test3> <img test4>';
// defining the regex
$re = "/<img.*>/U";
// put all matches into $matches
preg_match_all($re, $e, $matches);
// start creating the result
$result = "<p class='images'>";
// loop to get all the images
for($i=0; $i<count($matches[0]); $i++) {
    $result .= $matches[0][$i];
}
// print the final result
echo $result."</p>";

DEMO2

改进该代码的另一种方法是使用函数式编程(例如array_reduce)。但我会把它留作作业。

注意:还有另一种方法可以完成此操作,即解析 html 文档并使用 XPath 查找元素。查看 this answer 了解更多信息。