在内容上的图像之后插入字符串


Insert string after images on content

我有一个字符串

<p>content</p>
<p><img src="1.jpg" alt="alt image 1"></p>
<p>other content</p>
<p><img src="2.jpg" alt="alt image 2"></p>

我想获得Alt图像并插入图像后,如

<p>content</p>
<p><img src="1.jpg" alt="alt image 1"></p><p>alt image 1</p>
<p>other content</p>
<p><img src="2.jpg" alt="alt image 2"></p><p>alt image 2</p>

i know get Alt by

preg_match_all("/< *img[^>]*alt *= *['"'']?([^'"'']*)/i",$str,$alt);
foreach ($alt[1] as $alti) {
$altimg[]=$alti;
}

,我试过这个代码

for($i=0;$i < count($alt[1] );$i++){
    $regex = '#<img.+?src="([^"]*)".*?/?>#i';
    $replace = '$0<div>'.$altimg[$i].'</div>';
}
$str = preg_replace($regex, $replace, $str);

但结果显示

<p>content</p>
<p><img src="1.jpg" alt="alt image 1"></p><p>alt image 2</p>
<p>other content</p>
<p><img src="2.jpg" alt="alt image 2"></p><p>alt image 2</p>

请告诉我如何解决这个问题,谢谢你的帮助,抱歉我的英语不好。

这可以解决问题:

$regex = '#<img.+?src="([^"]*)".*?alt *= *['"'']?([^'"'']*)['"'']?.*?/?>#i';
$replace = '$0<p>$2</p>';
$str = preg_replace($regex, $replace, $str);

有两种方法:

  1. 简单的客户端方式:

    $("img").closest("p").after("<p>Content</p>");
    
  2. 艰难的PHP方式使用简单的HTML DOM解析器:

    $html = '';
    foreach($html->find('img') as $element) 
       echo $element->src . '<br>';
    

你的台词

$str = preg_replace($regex, $replace, $str);

在循环之外,将使用$regex &$replace在退出for循环后,因此它插入最后找到的alt。