从一个PHP字符串中提取2个数字

时间:2012-07-25 18:18:27

标签: php regex

我有像下面的字符串变量,它有两个数字的字符串

EUR 66,00 + EUR 3,90 Versandkosten

我需要提取两个数字 - 分别为66,00和3,98两个变量。任何人都可以告诉你如何做到这一点

5 个答案:

答案 0 :(得分:5)

  

我需要提取两个数字 - 分别为66,00和3,98两个变量。任何人都可以告诉你如何做到这一点

在PHP中有很多很多(也有很多)方法可以做到这一点。这是一对夫妇。

1. sscanf($subject, 'EUR %[0-9,] + EUR %[0-9,]', $one, $two);

2. preg_match_all('/[\d,]+/', $subject, $matches); list($one, $two) = $matches[0];

答案 1 :(得分:2)

如果字符串总是这样,那么正则表达式应该起作用:

$string = "EUR 66,00 + EUR 3,90 Versandkosten";
preg_match("/([0-9,]+).+([0-9,]+)/", $string, $matches);
var_dump($matches[1], $matches[2]);

答案 2 :(得分:2)

考虑这个字符串

$string = 'EUR 66,00 + EUR 3,90 Versandkosten';
$ar=explode($string,' ');
$a=$ar[1];
$b=$ar[4];

答案 3 :(得分:1)

preg_match('#([0-9,]+).*?([0-9,]+)#', $String, $Matches);

您的号码将在$Matches[1]$Matches[2]

答案 4 :(得分:0)

这是正确的:

<pre>
<?php
// 1The given string
$string = 'EUR 66,00 + EUR 3,90 Versandkosten';
// 2Match with any lowercase letters
$pattern[0] = '/[a-z]/';
// 3Match with any uppercase letters
$pattern[1] = '/[A-Z]/';
// 4Match with any commas
$pattern[2] = '/(,)/';
// 5Match with any spaces
$pattern[3] = '/( )/';
// 6 Remove the matched strings
$stripped = preg_replace($pattern,'',$string);
// Split into array from the matched non digit character + in this case.
$array = preg_split('/[\D]/',$stripped);
print_r($array);
?>
</pre>
相关问题