0

I have a text string in which I'd like to replace a pattern that occurs multiple times with a tag, like this:

<?php
$str = 'A *word* is a *word*, and this is another *word*.';
preg_replace('/\*([^$]+)\*/', '<b>$1</b>', $str);
?>

However, the function is replacing the whole range from the first asterisk to the last asterisk, i.e. it doesn't separately enclose each pattern with the tag, which is what I'm trying to accomplish.

A-Xepro
  • 29
  • 6

1 Answers1

1

Try making the pattern lazy:

$str = 'A *word* is a *word*, and this is another *word*.';
$out = preg_replace('/\*([^$]+?)\*/', '<b>$1</b>', $str);
echo $out;               //  ^^ change here

This prints:

A <b>word</b> is a <b>word</b>, and this is another <b>word</b>.

For an explanation of the minor change to your regex, the updated pattern says to:

\*        match *
([^$]+?)  followed by any character which is NOT $, one or more times,
          until reaching the
\*        FIRST closing *
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360