开发者

using php preg_match

开发者 https://www.devze.com 2023-01-14 10:58 出处:网络
I am trying to us开发者_开发技巧e PHP preg_math parse a string that looks like: 6.15608128 Norwegian kroner

I am trying to us开发者_开发技巧e 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.


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


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.


Are you enclosing your pattern in slashes?

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


Try this:

$s = '6.15608128 Norwegian kroner';

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

精彩评论

暂无评论...
验证码 换一张
取 消