2014-11-05 20 views
0

我想從一些字符串中提取號碼,並將其封裝成......這件事情是這樣的:PHP - 提取號碼,並將其封裝成<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,但我不知道如何...

韓國社交協會...

+0

整數? – 2014-11-05 19:55:34

回答

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

完美.. Tks很多... – giordanolima 2014-11-05 19:56:28

2

\d+匹配連續數字,$0把比賽中替換字符串

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

編輯:完全相同的功能得到張貼1分鐘前。我想這裏有一個確定的答案。只有

+0

好.. Tks解釋... – giordanolima 2014-11-05 19:58:35

0

嘗試......

$tok = strtok($string1, ' '); 

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