PHP-提取数字并将其封装到<;span>;


PHP - Extract numbers and enclose them into <span>

我想从一些字符串中提取数字,并将它们封装到。。。它是这样的:

$string1 = "Up to 3 bedrooms";
$string2 = "With 2 and 3 (wathever)";
echo myMagicFunction($string1); // Up to <span>3</span> bedrooms.
echo myMagicFunction($string2); // With <span>2</span> and <span>3</span> (wathever).

我想我可以用preg_replace,但我不知道怎么做。。。

Tks。。。

function myMagicFunction($str)
{
    return preg_replace('/'d+/', '<span>$0</span>', $str);
}

'd+匹配连续数字,$0将匹配项放入替换字符串

function myMagicFunction($string) {
    return preg_replace('/'d+/', '<span>$0</span>', $string);
}

编辑:1分钟前发布了完全相同的功能。我想这里有一个明确的答案。

试试这个。。。

$tok = strtok($string1, ' ');
$result = "";
while ($tok !== false) {
 if ( is_numeric($tok) )
    $result .= "<span>" . $tok . "</span>";
 else
    $result .= $tok;
 $tok = strtok(" 'n't");
}