0

I am trying to extract any number out from a string (with or without decimal) and dump that into an array. Below is my code

$matches = array();
$str = "I have string of 21.11 out of 30";
preg_match_all("/\d+/",$str,$matches);
echo var_dump($matches);

The current output has 3 elements below:

21

11

30

But I expect to output only 2 elements below:

21.11

30

How do I change my regex?

Liju Thomas
  • 1,054
  • 5
  • 18
  • 25

1 Answers1

1

You should use this regex (add dot in character class) :

$matches = array();
$str = "I have string of 21.11 out of 30";
preg_match_all("/[\d\.]+/",$str,$matches);
var_dump($matches);

Test it (Ctrl + Enter)

Samuel Dauzon
  • 10,744
  • 13
  • 61
  • 94