julio
julio

Reputation: 6758

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.

Upvotes: -1

Views: 705

Answers (5)

mickmackusa
mickmackusa

Reputation: 48071

This is an ideal scenario to call sscanf() because it will match the leading numeric string entirely AND produce a float-type value (instead of a string like preg_ functions do).

Code: (Demo)

$text = '6.15608128 Norwegian kroner';
sscanf($text, '%f', $price);
var_dump($price);
// float(6.15608128)

For an even lighter approach simply cast the string to a float. (Demo)

$text = '6.15608128 Norwegian kroner';
var_dump((float) $text);
// float(6.15608128)

Upvotes: 0

Robin
Robin

Reputation: 4260

Try this:

$s = '6.15608128 Norwegian kroner';

preg_match('/[0-9]*\.[0-9]*/', $s, $matches);
var_dump($matches);

Upvotes: 1

sholsapp
sholsapp

Reputation: 16080

Are you enclosing your pattern in slashes?

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

Upvotes: 1

Jim
Jim

Reputation: 18863

Without having the actual code, here is some code that does work:

$string = "6.15608128 Norwegian kroner";
preg_match('#[0-9\.]+#', $string, $matches); 

print_r($matches);

/* Outputs:

     Array
    (
        [0] => 6.15608128
    )
*/

The # signs are delimiters. For more information on the regex with php, see this article.

Upvotes: 3

kennytm
kennytm

Reputation: 523754

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

Upvotes: 5

Related Questions