Reputation: 1
i have a string as
<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>
i want to get alt images and insert after image, like
<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;
}
and i was try this code
for($i=0;$i < count($alt[1] );$i++){
$regex = '#<img.+?src="([^"]*)".*?/?>#i';
$replace = '$0<div>'.$altimg[$i].'</div>';
}
$str = preg_replace($regex, $replace, $str);
but the result show
<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>
please tell me how to fix this, thank for your help and Sorry for my bad english.
Upvotes: 0
Views: 129
Reputation: 570
This can solves problem:
$regex = '#<img.+?src="([^"]*)".*?alt *= *[\"\']?([^\"\']*)[\"\']?.*?/?>#i';
$replace = '$0<p>$2</p>';
$str = preg_replace($regex, $replace, $str);
Upvotes: 1
Reputation: 2016
Your line
$str = preg_replace($regex, $replace, $str);
is outside of the loop and will be running with the last value of $regex & $replace after exiting the for loop, hence it's inserting the last found alt.
Upvotes: 0
Reputation: 167182
You can do in two ways:
Easy client-side way:
$("img").closest("p").after("<p>Content</p>");
Tough PHP Way using Simple HTML DOM Parser:
$html = '';
foreach($html->find('img') as $element)
echo $element->src . '<br>';
Upvotes: 0