正则表达式以获取数字和小数

时间:2022-07-08 21:13:57

I'm trying to access

我正在尝试访问

1.20163

1.20163

from the following:

来自以下内容:

1 British Pound Sterling = 1.20163 Euro

1英镑= 1.20163欧元

So far I have:

到目前为止我有:

$exchange['rate'] = $xml->channel->item[15]->description;
$rate = preg_match('/^[0-9]{1,}$/', '', $exchange['rate']);

However, this seems to returns

然而,这似乎回归

1 British Pound Sterling = 1.20163 Euro

1英镑= 1.20163欧元

Any ideas?

有任何想法吗?

3 个解决方案

#1


3  

I think you using preg_match wrong You want to extract the value of 1.20163 from the string, right? Then do this:

我认为你使用preg_match错误你想从字符串中提取1.20163的值,对吧?然后这样做:

$s = '1 British Pound Sterling = 1.20163 Euro';
preg_match('/([0-9]+\.[0-9]+)/', $s, $matches);
$result = $matches[0];

You got your result in $result.

你得到$ result的结果。

#2


0  

/^[0-9]{1,}$/

means you want to match a line containing only numbers. You wont get any match in your case. You also use preg_match in a wrong way. See the documentation.

表示您想匹配仅包含数字的行。在你的情况下,你不会得到任何匹配。你也以错误的方式使用preg_match。请参阅文档。

Try something like:

尝试以下方法:

$exchange['rate'] = $xml->channel->item[15]->description;
preg_match('/=\s*([0-9.]+)\s/', $exchange['rate'], $matches);
// the result will be in $matches
$rate = $matches[1];

#3


0  

Try

尝试

'/([0-9]{1,}\.[0-9]{1,}) /'

Match numbers then decimal then numbers then space.

匹配数字,然后是小数,然后是数字,然

#1


3  

I think you using preg_match wrong You want to extract the value of 1.20163 from the string, right? Then do this:

我认为你使用preg_match错误你想从字符串中提取1.20163的值,对吧?然后这样做:

$s = '1 British Pound Sterling = 1.20163 Euro';
preg_match('/([0-9]+\.[0-9]+)/', $s, $matches);
$result = $matches[0];

You got your result in $result.

你得到$ result的结果。

#2


0  

/^[0-9]{1,}$/

means you want to match a line containing only numbers. You wont get any match in your case. You also use preg_match in a wrong way. See the documentation.

表示您想匹配仅包含数字的行。在你的情况下,你不会得到任何匹配。你也以错误的方式使用preg_match。请参阅文档。

Try something like:

尝试以下方法:

$exchange['rate'] = $xml->channel->item[15]->description;
preg_match('/=\s*([0-9.]+)\s/', $exchange['rate'], $matches);
// the result will be in $matches
$rate = $matches[1];

#3


0  

Try

尝试

'/([0-9]{1,}\.[0-9]{1,}) /'

Match numbers then decimal then numbers then space.

匹配数字,然后是小数,然后是数字,然