Returns the numeric value of the string

advertisements

This question already has an answer here:

  • Extract numbers from a string 15 answers

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;


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