2017-10-07 46 views
-1
$str = "SC - ESV Parndorf 2 - 5 SV Horn"; 
$str4 = explode(" - ", $str,2); 
$str5=$str4[0];  
$str6 = explode(" ", $str5); 
$Num=end($str6);   
$str7=$str4[1];  
$str8 = explode(" ", $str7); 
$Num1 = $str8[0]; 

如果我有兩個「 - 」,則無法將數字2和5取出。無法使用包含兩個連字符的爆炸分割

+0

歡迎stackoverflow.com!請閱讀[如何提問](https://stackoverflow.com/questions/how-to-ask),[如何創建一個最小,完整和可驗證的示例](https://stackoverflow.com/help/mcve ),然後相應地編輯您的問題。您可能還想查看網站,瞭解更多關於如何在這裏工作的信息。 – wp78de

+0

我想提取分數。 –

+0

答案很有幫助,但是......「感謝您的反饋!記錄下那些名聲不到15的人的投票記錄,但不要更改公開顯示的帖子分數。」 –

回答

0

我建議使用正則表達式來替代,例如(^.+) (\d+) - (\d+) (.+$)
preg_match_all()這樣一起:

$re = '/(^.+) (\d+) - (\d+) (.+$)/'; 
$str = 'SC - ESV Parndorf 2 - 5 SV Horn'; 
preg_match_all($re, $str, $matches); 
foreach ($matches as $match) { 
    echo $match[0] . "\n"; 
} 

根據你的問題,你最感興趣的捕獲組2和3,RESP。 $matches[2][0]$matches[3][0]

+0

兩個建議函數的區別在於:'preg_match'在第一場比賽後停止。 'preg_match_all'繼續查找,直到完成處理整個字符串。如果你有一個匹配preg_match的單個字符串就足夠了,否則preg_match_all會更好。 http://php.net/manual/en/function.preg-match-all.php – wp78de

0

對於這樣的工作,你最好使用preg_match

$re = '/(\d+)\s+-\s+(\d+)/'; 
$str = 'SC - ESV Parndorf 2 - 5 SV Horn'; 
preg_match($re, $str, $matches); 
print_r($matches); 

說明:

/   : regex delimiter 
    (\d+) : group 1, 1 or more digits 
    \s+-\s+ : a dash between some spaces 
    (\d+) : group 2, 1 or more digits 
/   : regex delimiter 

輸出:

Array 
(
    [0] => 2 - 5 
    [1] => 2 
    [2] => 5 
) 
+0

@ wp78de:並非如此,您正在使用preg_match_all,並且您正在捕獲太多的羣組 – Toto