【问题标题】:How can i replace string beetwen tags <img src="example.com"/> in PHP?如何在 PHP 中替换标签 <img src="example.com"/> 之间的字符串?
【发布时间】:2015-08-12 21:21:39
【问题描述】:

如何在字符串中替换 &lt;img src="xxxx"&gt; 等标签之间的字符串?

$string ="<h1> hi, My name is Bob</h1><img src="www.ewrfcds.jpg"/> this is my pictures <img src="www.google.jpg"/>";

我需要将标签&lt;img src="www.google.jpg"/&gt;的内容修改为&lt;img src="www.myImages.jpg"/&gt;

期望的输出:

$string ="<h1> hi, My name is Bob</h1><img src="www.myImages1.jpg"/> this is my pictures <img src="www.myImages2.jpg"/>";

【问题讨论】:

标签: php string tags substring


【解决方案1】:

我意识到已经有一个与使用 DOM 相关的答案。不这样做,您可以使用 PHP 完成您需要的工作。

$string = '<h1> hi, My name is Bob</h1><img src="www.ewrfcds.jpg"/> this is my pictures <img src="www.google.jpg"/>';

// Get all the matches from the string
preg_match_all('/<img src="(.*?)"\/>/', $string, $matches);

// Create the regex pattern for each match
foreach($matches[1] as $match) {
    $patterns[] = '/' . $match . '/';
}

// Set the replacements
$replacements = array('www.myImages1.jpg', 'www.myImages2.jpg');

echo preg_replace($patterns, $replacements, $string);

输出:

<h1> hi, My name is Bob</h1><img src="www.myImages1.jpg"/> this is my pictures <img src="www.myImages2.jpg"/>

【讨论】:

    【解决方案2】:

    我建议您使用 DOM 而不是正则表达式。由于替换涉及多个不同的图像源,因此解决方案取决于您要如何指定要替换的图像。下面的代码将根据 URL 数组替换图像源。字符串中的第一个图像将获得数组的第一个源,依此类推。

    <?php
    
    $string     = '<h1> hi, My name is Bob</h1><img src="www.ewrfcds.jpg"/> this is my pictures <img src="www.google.jpg"/>';
    $imgUrls    = array('www.myImages1.jpg', 'www.myImages2.jpg');
    $doc        = new DOMDocument();
    $i          = 0;
    
    $doc->loadHTML($string);
    $images = $doc->getElementsByTagName('img');
    
    foreach($images as $image) {
    
        $image->setAttribute('src', $imgUrls[$i]);
        $i++;
    }
    
    $newString  = $doc->saveHTML();
    
    echo $newString;
    
    ?>
    

    输出:

    <h1> hi, My name is Bob</h1><img src="www.myImages1.jpg"> this is my pictures <img src="www.myImages2.jpg">
    

    【讨论】:

    • 看起来 OP 想用不同的 URL 替换每个图像源,考虑到它们有 'www.myImages1.jpg' 和 'www.myImages2.jpg'
    • 哦,我的错。感谢您的通知!
    猜你喜欢
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 2019-06-21
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    相关资源
    最近更新 更多