错误将图像标记替换为图像src

时间:2017-11-27 02:31:25

标签: php

$content = 'This fairy tale-like place is based on a story of two lovers who ran away to escape their enemies.
<img src="blisshouse-1.jpg"> <img src="blisshouse-2.jpg">';

preg_match_all('%<img.*?src=["\'](.*?)["\'].*?/>%i', $content, $matches);
if(count($matches) > 0) {
    foreach ($matches as $matche) {
        $content = preg_replace('%<img.*?src=["\'](.*?)["\'].*?/>%i', $matche[1], $content);
    }
}
echo $content;

结果是:

This fairy tale-like place is based on a story of two lovers who ran away to escape their enemies.
blisshouse-1.jpg blisshouse-1.jpg

错误无法将<img src="blisshouse-2.jpg">替换为blisshouse-2.jpg。如何解决它

1 个答案:

答案 0 :(得分:1)

正如@Mario建议的那样 - 只需使用 preg_replace

另外,我添加了 /?,因为 img 标记没有斜杠。

$content = 'This fairy tale-like place is based on a story of two lovers who ran away to escape their enemies.
<img src="blisshouse-1.jpg"> <img src="blisshouse-2.jpg">';

$content = preg_replace('%<img.*?src=["\'](.*?)["\'].*?/?>%i', '$1', $content);
echo $content;