2011-04-27 29 views
1

有這樣的字符串:PHP預浸比賽 - 正則表達式與浮點值

$var = "30.5x120.8 (test desc here)"; 

我需要走出去30.5和120.8用正則表達式。任何幫助? Thx

+0

如果您的正則表達式問題重複出現,請查看http://regular-expressions.info/以瞭解語法,或http: //stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world用於製作它們的工具。 – mario 2011-04-27 13:33:56

回答

14
preg_match_all('~\d+(?:\.\d+)?~', $string, $matches); 
var_dump($matches[0]); 
+0

也可以用整數嗎? – Ste 2011-04-27 13:29:26

+0

@Ste:我調整了它,所以它也適用於整數。 – NikiC 2011-04-27 13:30:17

+0

@Ste:30.5x.2呢?這是你想要支持的東西嗎? – 2011-04-27 13:34:07

8
$var = "30x120 (test desc here)"; 

preg_match_all('/^(\d+)x(\d+)/', $var, $matches); 

var_dump($matches) 

Ideone

輸出

array(3) { 
    [0]=> 
    array(1) { 
    [0]=> 
    string(6) "30x120" 
    } 
    [1]=> 
    array(1) { 
    [0]=> 
    string(2) "30" 
    } 
    [2]=> 
    array(1) { 
    [0]=> 
    string(3) "120" 
    } 
} 

更新

也爲17.5x17.5工作?

這是其中一個會...

/^(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)/ 

Ideone

+0

我想'的preg_match()'會更有意義(並進行輸出數組更容易解析)比'preg_match_all()'更容易,因爲主題字符串中只有一個模式出現。 – 2011-04-27 11:13:39

+0

@詹姆斯你是對的,我的壞習慣。 – alex 2011-04-27 11:15:06

+0

也適用於17.5x17.5? – Ste 2011-04-27 13:00:47

2
preg_match('/^(\d+)x(\d+)/', '30x120 (test desc here)', $result); 

,並使用$result[1]$result[2]

+0

meh - 與@Kevin同時貼近發佈 – 2011-04-27 10:59:37

+0

這通常是一個秒問題:p – 2011-04-27 11:01:11