PHP - 替换 <img> 标签并返回 src

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

任务是用

<img>
标签和
<div>
属性替换给定字符串中的所有
src
标签作为内部文本。 在寻找答案时,我找到了similar question

<?php

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

?>

结果:

this is something with an (image)  in it.

问题:如何升级script ant得到这个结果:

this is something with an <div>test.png</div>  in it.
php regex html-parsing
3个回答
18
投票

这是PHP的

DOMDocument
类擅长的问题:

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

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

$content = $dom->saveHTML();

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

0
投票
<?php
$strings = 'awdaw <img src="http://ua1.us/media/media.jpg" alt="Image" width="100" height="100"> aw <img src="http://ua1.us/media/media1awdwa.jpg"> wawadwad';

preg_match_all('/<img[^>]+>/i', $strings, $images);
foreach ($images[0] as $image) {
    preg_match('/src="([^"]+)/i', $image, $replacements);
    $replacement    = isset($replacements[1]) ? $replacements[1] : (isset($replacements[0]) ? $replacements[0] : "image");    
    $strings    = str_replace($image, $replacement, $strings);
}
echo $strings;
© www.soinside.com 2019 - 2024. All rights reserved.