Carlos Santos
Carlos Santos

Reputation: 13

PHP preg_match & preg_replace outputing wrong

<?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

Answers (1)

Sam
Sam

Reputation: 20486

There are two fundamental issues:

  • you don't need to use a preg_match() and a preg_replace(), you can just use preg_replace() and reference your capture groups in the substitution
  • it looks like you copy pasted some code from HTML regex, and have [^>]+ inside of your [img], which says 1+ non-> characters..it should really be [^\]]+, 1+ non-] characters

Final 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);

Demo: RegEx and PHP

Upvotes: 2

Related Questions