从字符串中获取整个img标签,包括其属性声明

问题描述 投票:0回答:4

我在 php.ini 的变量中有 html 字符串。我想从中获取标签。例如:

$str ='<p><img src="link"></p><p>text</p>';
   

如何从该字符串中获取

<img src="link">
(或任何
img
标签及其内容)?

php regex string html-parsing text-parsing
4个回答
3
投票

所有答案看起来都有点混乱,并且包含正则表达式。

你不需要它。

$str ='<p><img src="link"></p><p>text</p>';
echo strip_tags($str, '<img>');

会很好地工作。

Strip_tags 参考


2
投票

您可以使用正则表达式,但必须小心照顾可能位于其中的任何属性,或者您可以使用 DOMDocument::loadHTML 功能以及 DOMDocument::getElementsByTagName

$doc = new DOMDocument();

$doc->loadHTML($str);

// gets all img tags in the string    
$imgs = $doc->getElementsByTagName('img');

foreach ($imgs as $img) {    
    $img_strings[] = $doc->saveHTML($img);    
}

然后,您的所有 img 标签都在

$img_strings
变量中。

foreach
循环中,您还可以获取标签内的属性:
$img->getAttribute('src');


0
投票

如果我正确理解你想要做什么:

我会建议类似的东西 这里描述了什么。

他们创建了一个函数来选择两个特定字符串之间包含的字符串。这是他们的功能:

function getInnerSubstring($string,$delim){
    // "foo a foo" becomes: array(""," a ","")
    $string = explode($delim, $string, 3); // also, we only need 2 items at most
    // we check whether the 2nd is set and return it, otherwise we return an empty string
    return isset($string[1]) ? $string[1] : '';
}

只要您的 HTML 中没有另一组

""
,那么这应该适合您。

如果您使用此功能,您可以搜索仅在这两者之间的内容

"


-1
投票

php 中的用户正则表达式。你应该为它编写正则表达式

http://php.net/manual/en/function.preg-match.php

<img\s[^<>]*>
© www.soinside.com 2019 - 2024. All rights reserved.