Itai Sagi
Itai Sagi

Reputation: 5615

getting intval() using php?

let's say I have the following string:

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.

Upvotes: 2

Views: 497

Answers (4)

dnagirl
dnagirl

Reputation: 20446

$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!)

Upvotes: 1

hakre
hakre

Reputation: 198204

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);

Upvotes: 2

pb149
pb149

Reputation: 2298

<?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;

?>

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 238015

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.

Upvotes: 4

Related Questions