在内容中preg_replace image src时出错

时间:2018-09-28 03:40:47

标签: php

<?php
$content = 'Image 1 <img src="//placehold.it/100x100" /> and image 2 is <img src="//placehold.it/150x150" />';
preg_match_all('/<img[^>]+>/i',$content, $imgTags);
for ($i = 0; $i < count($imgTags[0]); $i++) {
    preg_match('/src="([^"]+)/i', $imgTags[0][$i], $imgage);
    $imag_src = str_ireplace( 'src="', '',  $imgage[0]);
    $image_url = "$i".$imag_src;
    $content = preg_replace("#(<img[^>]*>)#s", '<img src="'.$image_url.'" />', $content);
}
echo $content;
?>

结果无法替换精确位置图像src

Image 1 <img src="1//placehold.it/150x150"> and image 2 is <img src="1//placehold.it/150x150">

如何修复它以遵循此结果:

Image 1 <img src="1//placehold.it/150x150"> and image 2 is <img src="2//placehold.it/150x150">

1 个答案:

答案 0 :(得分:1)

如果您要做的是将图像编号添加到src链接的开头,则可以执行以下操作:

$content = 'Image 1 <img src="//placehold.it/100x100" /> and image 2 is <img src="//placehold.it/150x150" />';
echo preg_replace('/(Image\s+(\d+).*?<img src=")/i', '$1$2', $content);

输出:

Image 1 <img src="1//placehold.it/100x100" /> and image 2 is <img src="2//placehold.it/150x150" />

如果您还想将图像1更改为150x150,则可以使用以下方法:

echo preg_replace('/(Image\s+(\d+).*?<img src=")(.*?)\d+x\d+/i', '$1$2${3}150x150', $content);

输出:

Image 1 <img src="1//placehold.it/150x150" /> and image 2 is <img src="2//placehold.it/150x150" />