Reputation: 13
<?php
$string = "[img image:left]1.jpg[/img]Example Text 1[img image:left]2.jpg[/img] Example Text 2";
preg_match("/\[img\s*[^>]+\s*\](.*?)\[\/\s*img\]/i", $string, $match);
$result = preg_replace("/\[img\s*[^>]+\s*\](.*?)\[\/\s*img\]/i", $match['1'], $string);
echo $result;
?>
When using this code it should output 1.jpg
, Example Text 1
, 2.jpg
, Example Text 2
.
But however it shows only 2.jpg
, Example Text 2
.
I dont know what i'm doing wrong.
Upvotes: 1
Views: 214
Reputation: 20486
There are two fundamental issues:
preg_match()
and a preg_replace()
, you can just use preg_replace()
and reference your capture groups in the substitution[^>]+
inside of your [img]
, which says 1+ non->
characters..it should really be [^\]]+
, 1+ non-]
charactersFinal solution:
$string = "[img image:left]1.jpg[/img]Example Text 1[img image:left]2.jpg[/img] Example Text 2";
$string = preg_replace("/\[img\s*[^\]]+\s*\](.*?)\[\/\s*img\]/i", ' \1 ', $string);
Upvotes: 2