getting intval() using php?
let's say I have the following string:
开发者_StackOverflow社区danger13 afno 1 900004
using intval()
it gives me 13, however, I want to grab the highest integer in the string, which is 9000004, how can I achieve this?
Edit: the string comes in different forms, and I don't know where the highest number will be.
You'll need to get all the integers out of the string, then find the biggest...
$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
is now 900004
.
Note that this is very simple. If your string has anything that matches the pattern \d+
(1 or more digits) that you don't want to match as a separate integer (e.g. 43.535
would return 535
), this won't be satisfactory for you. You'll need to define more closely what you mean.
For the lexicographical highest integer value within the string (up to PHP_INT_MAX
) you can just split the numbers apart and get the maximum value:
$max = max(preg_split('/[^\d]+/', $str, NULL, PREG_SPLIT_NO_EMPTY));
Demo.
Or better self-documenting:
$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);
$nums=preg_split('/[^\d\.]+/',$string); //splits on non-numeric characters & allows for decimals
echo max($nums);
ETA: updated to allow for "words" that end in or contain numbers (Thanks Gordon!)
<?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;
?>
精彩评论