PHP preg_replace 在同一个字符串中多次出现一个模式

PHP preg_replace a pattern multiple times in the same string

我有一个文本字符串,我想在其中用标记替换多次出现的模式,如下所示:

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

但是,该函数正在替换从第一个星号到最后一个星号的整个范围,即它没有用标签单独包含每个模式,这正是我想要完成的。

尝试制作模式懒惰:

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

这会打印:

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

为了解释对正则表达式的细微更改,更新后的模式如下:

\*        match *
([^$]+?)  followed by any character which is NOT $, one or more times,
          until reaching the
\*        FIRST closing *