PHP preg_在同一字符串中多次替换模式

问题描述 投票:0回答:1

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

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

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

php regex preg-replace
1个回答
0
投票

尝试制作图案lazy

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

此打印:

A <b>word</b> is a <b>word</b>, and this is another <b>word</b>.
© www.soinside.com 2019 - 2024. All rights reserved.