2

Hi I hope someone can help, as not too hot on regular expressions.

Got a script snippet as follows..

<?php

$news="test message {image=abc} more text text text {image=def}";

$news=preg_replace_callback("/\{image=.*\}/i",function ($matches) { $field=$matches[0];  return "*".$field."*"; }, $news);


echo $news;

?>

However when i run it, it returns

test message *{image=abc} more text text text {image=def}*

Instead I want it to return..

test message *{image=abc}* more text text text *{image=def}*

Thanks for any help.

2 Answers2

1

Make your regex non-greedy by using .*? instead of .*:

$news = "test message {image=abc} more text text text {image=def}";
$news = preg_replace_callback("/\{image=.*?\}/i",function ($matches) { 
                 return "*".$matches[0]."*"; }, $news);

echo $news;

OUTPUT

test message *{image=abc}* more text text text *{image=def}*
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

Why callback?

$news = preg_replace("/(\{image=[^\}]+\})/i", "*$1*", $news);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87