Search code examples
phpregexpreg-matchtext-extractiontext-parsing

Get the leading float value from a string


I am trying to use PHP preg_math parse a string that looks like:

6.15608128 Norwegian kroner

I just want the first part (the digits), not the text. I wrote a simple regex like

[0-9\.]+ 

that works fine in regex testers, but PHP complains about the '+'. Can anyone help me write this regex so it's valid for the preg_match() function? I've tried a ton of different ideas but I'm really not too knowledgeable with regex.


Solution

  • The regex works fine. Are you missing the delimiters? The function should be used like this:

    preg_match('/[0-9\.]+/', $string, $result);
    

    (BTW, you don't need to escape the . inside the character class. [0-9.] is enough.)