如何在找到的子字符串的两边添加字符串

时间:2015-02-25 19:06:34

标签: php regex

我有一个输入字符串:

10 birds have found 5 pears and 6 snakes.

如何将html标记放在使用正则表达式找到的子字符串周围?

例如,我希望所有数字都是粗体,如下所示:

 <b>10</b> birds have found <b>5</b> pears and <b>6</b> snakes.

2 个答案:

答案 0 :(得分:1)

您可以尝试使用preg_replace()功能:

$str = '10 birds have found 5 pears and 6 snakes.';
echo preg_replace('/(\d+)/', '<b>$1</b>', $str);

输出:

<b>10</b> birds have found <b>5</b> pears and <b>6</b> snakes.

答案 1 :(得分:0)

如果没有正则表达式,你可以这样做:

$items = explode(' ', $text);
$result = array_reduce($items, function ($c, $i) {
    return ($c ? $c . ' ' : $c)
         . (is_numeric($i) ? '<b>' . $i . '</b>' : $i);
});