views:

48

answers:

4

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

Thanks for any tips.

+4  A: 

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

KennyTM
Thanks a lot Kenny, you're right, I was missing the delimiters.
julio
As you may have guessed I'm messing with the Google currency conversion API. The issue is that they are pretty non-standard with their data, it's not true JSON etc. Some of the currency rates have spaces rather than commas or other separators-- eg: 1 811.5942 Columbian pesosIs there a way to alter this regex to include that space? Again, in a normal regex you'd just add a space after the dot ([0-9\. ]) but this doesn't work in the PHP.Thanks again.
julio
@julio: `[0-9. ]` must work (but that would include the space before 'Columbian' too). If not, try `[0-9.\s]`. If the problem is due to the extra space, try `[\d\s]+\.\d+`.
KennyTM
you're right, the regex you posted does work. I had an issue due to non-UTF-8 characters.Thanks again
julio
+3  A: 

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.

Brad F Jacobs
A: 

Are you enclosing your pattern in slashes?

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

gnucom
It does not *have* to be slashes, just has to be a valid delimiter, as an fyi :)
Brad F Jacobs
Neato - didn't know that.
gnucom
A: 

Try this:

$s = '6.15608128 Norwegian kroner';

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