PHP - replace <img> tags and return src

戏子无情 提交于 2019-12-10 03:31:37

问题


Mission is to replace all <img> tags in given string with <div> tags and src property as inner text. In search for the answer I found similar question

<?php

    $content = "this is something with an <img src=\"test.png\"/> in it.";
    $content = preg_replace("/<img[^>]+\>/i", "(image) ", $content); 
    echo $content;

?>

result:

this is something with an (image)  in it.

Question: How to upgrade script ant get this result:

this is something with an <div>test.png</div>  in it.

回答1:


This is the kind of problem that PHP's DOMDocument class excels at:

$dom = new DOMDocument();
$dom->loadHTML($content);

foreach ($dom->getElementsByTagName('img') as $img) {
    // put your replacement code here
}

$content = $dom->saveHTML();



回答2:


$content = "this is something with an <img src=\"test.png\"/> in it.";
$content = preg_replace('/(<)([img])(\w+)([^>]*>)/', '<div>$1</div>', $content); 
echo $content;


来源:https://stackoverflow.com/questions/13783760/php-replace-img-tags-and-return-src

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!