2

我需要你的帮助相关的 php。在 php 中,我只想允许 html<img>标签,我尝试了 php 的内置函数strip_tags(),但它没有给我我需要的输出。例如,在下面的代码中strip_tags()允许 img 标签,但与文本一起。

$img = "<img src='/img/fawaz.jpg' alt= ''> <br /> <p> This is a detailed paragraph about Fawaz and his mates.</p>";
echo strip_tags($img , "<img>");

仅允许<img>或仅来自函数或变量的任何标记的正确方法是什么。任何帮助将不胜感激。

谢谢

4

3 回答 3

5

这可能是由于您的代码中没有关闭 img 标记。试试这个

$img = "<img src='/img/fawaz.jpg' alt= '' /> <br /> <p> This is a detailed paragraph about Fawaz and his mates.</p>";
echo strip_tags($img , "<img>");
于 2010-11-25T06:52:12.820 回答
2

strip_tags()不能按照您希望的方式工作。如果提供了第二个参数,则列出的标签允许成为结果字符串的一部分 - 未列出的标签除外。它不会过滤掉内部文本。

如果您只想提取<img/>元素,甚至不要考虑使用正则表达式。为此使用 DOM 解析器:

libxml_use_internal_errors(true);
$doc=new DOMDocument;
$html=$doc->loadHTML('<img src="/img/fawaz.jpg" alt= ""> <br /> <p> This is a
detailed paragraph about Fawaz and his mates.</p>');
$path=new DOMXPath($doc);
foreach ($path->query('//img') as $found)
    var_dump($doc->saveXML($found));
于 2010-11-25T07:07:22.497 回答
1

<img>删除没有and <a>and <br/>and and and的HTML标签<hr/>...

$img = "
        <img src='/img/fawaz.jpg' alt= '' />
        <br /><br/>
        <hr/>
        <p> This is a detailed paragraph about Fawaz and his mates.</p>
        <a href='cft'>123</a>
        ";
$img = strip_tags($img , "<img>|<a>|<br>|<hr>");
echo $img;
于 2013-06-27T13:28:42.900 回答