2017-03-23 48 views
0

我的字符串看起來象下面這樣:如何從字符串中捕獲所有數字子字符串?

Response: 311768560 
311768562 
311768564 

我曾嘗試:

$success_pattern="Response: ((\d+)[\n])*"; 
$response="Response: 311768560\n311768562\n311768564\n311768566"; 
preg_match("/$success_pattern/i", $response, $match); 

輸出:

Array ( 
    [0] => Response: 311768560 311768562 311768564 
    [1] => 311768564 
    [2] => 311768564 
) 

我需要一個包含所有的數字像輸出數組:

array('311768560','311768562','311768564'); 
+0

只要你想preg_match然後讓我知道,它是固定的,會有3個數字? –

回答

0
<?php 

$string="Response: 311768560 311768562 311768564"; 
preg_match_all("/[\d]+/", $string, $matches); 
print_r($matches); 

輸出:

Array 
(
    [0] => Array 
     (
      [0] => 311768560 
      [1] => 311768562 
      [2] => 311768564 
     ) 

) 
+0

非常感謝你的回答,但我只想用preg_match而不是preg_match_all – mateors

+0

@mateors爲了找到多個匹配你必須去'preg_match_all' –

+0

我參考這個網站https://regex101.com/他們說A重複捕獲組將只捕獲最後一次迭代。如果你對數據不感興趣,那麼在重複組中放置一個捕獲組來捕獲所有迭代或者使用非捕獲組,所以我想應該有一個解決方案,你確定preg_match_all是唯一的解決方案嗎?在此先感謝您的幫助。 – mateors

-1

使用Array_shift()函數

<?php 
$str = "Response: 311768560 311768562 311768564"; 
$s = explode(" ",$str); 
$p = array_shift($s); 
print_r($s); 
?> 

輸出

Array (
    [0] => 311768560 
    [1] => 311768562 
    [2] => 311768564) 
+0

謝謝,但我只需要使用preg_match – mateors

+0

你已經改變了輸入,以適應你的方法。 '$ str'不能準確地表示OP的採樣輸入。 – mickmackusa

0

儘量不要太掛像preg_match()特定的功能。 PHP提供了幾種方法來生成你想要的輸出。我會告訴你三種不同的方法:

輸入

$response="Response: 311768560 
311768562 
311768564"; 

方法#1explode()substr()strpos()Demo

$array=explode("\r\n",substr($response,strpos($response,' ')+1)); 

*注意,這種方法假定第一個字符串(Response)是唯一不需要的子字符串,並且它總是首先。另外,根據您的編碼環境,\r可能不是必需的。這可能是我的方法列表中最快的,因爲它不使用正則表達式,但它確實需要3個函數調用和一個增量 - 更不用說它可能太實際用於實際用例。

方法#2preg_match_all()Demo

$array=preg_match_all('/\d+/',$response,$out)?$out[0]:[]; 

這種方法是非常直接的,快速,需要最少的代碼。如果有任何缺點,那麼preg_match_all()會返回true | false結果並以多維數組的形式生成輸出變量。要修改此輸出以適合您的一維要求,我在函數的末尾放置了一個內聯條件,它將所需數據傳遞到$array

方法#3preg_split()Demo

$array=preg_split('/[^\d]+/',$response,null,PREG_SPLIT_NO_EMPTY); 

此功能的行爲就像除了它explode()揮動正則表達式的功率。該模式標識所有非數字子串,並將它們用作「分隔符」,並將它們分割成每個子串。對於你的輸入,第一個分隔符是「Response:」,然後是「311768560」和「311768562」之後的換行符。 preg_split()的美妙之處在於它直接提供您正在尋找的一維數組。

輸出

無論哪個你試試上面的方法,你會收到相同的正確的輸出:$array=array('311768560','311768562','311768564');

如果這些方法都失敗了您的實際使用情況,那麼它可能是您的$response字符串的產品與您在此處發佈的樣本數據太不相同。

相關問題