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

3
  • Welcome. Please take the time to format your question. Commented Jun 2, 2014 at 22:28
  • Thanks, i'll rephrase it the best i can, i'm new to coding didnt knew how to correctly write my question Commented Jun 2, 2014 at 22:34
  • @CarlosSantos: Your question was perfectly understandable, I was only speaking about the format. Commented Jun 2, 2014 at 23:27

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.