2012-07-25 23 views
-4

號我有一個像它下面有一個字符串有兩個數字提取2從一個字符串中PHP

EUR 66,00 + EUR 3,90 Versandkosten 

我需要提取兩個數字前的字符串變量 - 無論是66,00和3,98分別向兩個變量。誰能告訴如何做到這一點

回答

5

我需要提取兩個數字 - 6600和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

第二個是完美的工作 – 2012-07-25 19:40:31

2

如果字符串總是看起來像這樣的正則表達式,像這樣應該努力:

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

你想中間部分是非貪婪:'+'。?。否則[它會吃得太多](http://viper-7.com/jPJEaW)的字符串。 – nickb 2012-07-25 18:22:21

+0

您可以用'[^ ​​\ d] +'替換'。+',以匹配非數字字符嗎?我的正則表達式有點生鏽.... – andrewsi 2012-07-25 18:24:20

+0

輸出是 Array([0] => 66,00 + EUR 3,90 [1] => 66,00 [2] => 3,90) – 2012-07-25 18:56:22

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

你的號碼將在$Matches[1]$Matches[2]

+0

this也得到數組([0] => 66,00 + EUR 3,90 [1] => 66,00 [2] => 3,90) – 2012-07-25 18:58:10

+0

是的,我知道。你在這裏有什麼意思? – mdziekon 2012-07-25 18:58:50

+0

只需要66,00和3,90相似的數字, – 2012-07-25 19:01:32

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> 
+0

這個retuns Array([0 ] => 6600 [1] => 390) 錯過了,:) – 2012-07-25 19:00:09

+1

你可以刪除$ pattern [2] ='/(,)/'; – 2012-07-25 19:01:18

+0

酷伴侶,謝謝 – 2012-07-25 19:06:28

2

考慮這個字符串

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