2011-09-14 28 views
2

讓我們說我有以下字符串:獲取intval()使用PHP?

danger13 afno 1 900004 

使用intval()它給了我13,但是,我要搶在字符串中的最大整數,這是9000004,我怎麼能做到這一點?

編輯:字符串以不同的形式出現,我不知道最高的數字將在哪裏。

+3

的方法之一是字符串分割到使用'爆炸()',走過每個成員的數組,找到最高的國家之一 –

+1

請問字符串總是具有相同格式?你想要字符串中的「最高數字」還是總是*字符串中最後一個數字*? – deceze

+4

'intval('danger13 afno 1 900004')'不給你'13'。 – salathe

回答

4

你需要把所有的整數出來的字符串,然後找到最...

$str = "danger13 afno 1 900004"; 
preg_match_all('/\d+/', $str, $matches); // get all the number-only patterns 
$numbers = $matches[0]; 

$numbers = array_map('intval', $numbers); // convert them to integers from string 

$max = max($numbers); // get the largest 

$max現在900004

請注意,這是很簡單。如果您的字符串中有任何與您不希望以單獨整數匹配的模式\d+(1個或更多數字)匹配(例如,43.535將返回535),則這不會令您滿意。你需要更仔細地定義你的意思。

0
<?php 

$string = 'danger13 afno 1 900004'; 

preg_match_all('/[\d]+/', $string, $matches); 

echo '<pre>'.print_r($matches,1).'</pre>'; 

$highest = array_shift($matches[0]); 

foreach($matches[0] as $v) { 
    if ($highest < $v) { 
    $highest = $v; 
    } 
} 

echo $highest; 

?> 
1
$nums=preg_split('/[^\d\.]+/',$string); //splits on non-numeric characters & allows for decimals 
echo max($nums); 

ETA:更新,以便「單詞」在年底或字符串(最多PHP_INT_MAX)中包含數字(感謝戈登!)

+1

@戈登:點了。 'preg_split'並在max之前過濾掉alpha會更好。 – dnagirl

2

對於辭書最高的整數值即可只需拆分數字並獲得最大值:

$max = max(preg_split('/[^\d]+/', $str, NULL, PREG_SPLIT_NO_EMPTY)); 

Demo

或者更好的自我記錄:我想到的

$digitsList = preg_split('/[^\d]+/', $str, NULL, PREG_SPLIT_NO_EMPTY); 
if (!$digitsList) 
{ 
    throw new RuntimeException(sprintf('Unexpected state; string "%s" has no digits.', $str)); 
} 
$max = max($digitsList);