0

Title is pretty much self explanatory but just to clarify.

I want to fetch the numeric value out of string witch is not necessarily contains only numeric values.

Now I can do that with preg_match but I was wondering if there is an internal php command that can do it in a cleaner way.

so... just to clarify with example:

$myString = 'qazwsxedc15rfvtgbyhnujmikolp';
$myString = fetchNumber($myString); //Expecting to get $myString=15;
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
iprophesy
  • 175
  • 3
  • 9
  • 5
    Maybe this is a good solution? http://stackoverflow.com/questions/6278296/extract-numbers-from-a-string/12582416#12582416 – JimboSlice Jan 06 '15 at 13:35

2 Answers2

2

I don't believe there's an out of the box function that can fetch numbers from a string. There are certain conventions such as strings beginning with numbers can be type casted to integers.

Anyway, preg_match might not be optimal. Consider using preg_replace

function fetchNumber($string)
{
  $string = preg_replace('#[^\d]*#', '', $string);
  return (int)$string;
}

$myString = 'qazwsxedc15rfvtgbyhnujmikolp';
$myString = fetchNumber($myString); //Expecting to get $myString=15;

var_dump($myString);

You do lose the "dot" that can signal floats, but your scenario excluded this possibility as far as I noticed.

Live Example on sandbox.onlinephpfunctions.com

Khez
  • 10,172
  • 2
  • 31
  • 51
  • Thanks bro ! I just find out that it IS possible to get it right of the box with intval(filter_var($matches[0], FILTER_SANITIZE_NUMBER_INT)); Working Perfectly !!! – iprophesy Jan 06 '15 at 13:48
  • `[^\d]` is the same as `\D`. `*` doesn't make a lot of sense -- why match a zero with string and replace it with an empty string. I think it should be `/\D+/`. – mickmackusa Oct 31 '22 at 07:07
1

Try something like this

$str = 'qazwsxedc15rfvtgbyhnujmikolp';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
dsn
  • 67
  • 2
  • 11