2017-05-05 68 views
0

我試圖使用preg_match_all()函數在_之後搜索字符串。我想要的輸出將是reset,text,email。我試圖使用regexr編輯器並使其能夠與[_]+[a-z]*合作,但這將包括_reset, _text, _text。該字符串將是:在下劃線之前或之後提取子字符串

$str = 'button_reset,location_text,email_text'; 

預期輸出:

reset 
text 
email 
+0

你期望的輸出是沒有意義的。 「email」不在下劃線之後。 –

回答

2

這將是更好地避免正則表達式這任務,只是使用str_replace()

輸入:

$str = 'button_reset,location_text,email_text'; 

代碼爲陣列輸出:

var_export(explode(',',str_replace(['button_reset','location_text','email_text'],['reset','text','email'],$str))); 
// array (
// 0 => 'reset', 
// 1 => 'text', 
// 2 => 'email', 
//) 

或者,如果你堅持,正則表達式(Demo Link):

/button_\K[^,]+|,location_\K[^,]+|,\K[^_]+(?=_text)/ 

正則表達式擊穿:

button_\K[^,]+  #Match one or more non-comma-characters after button_ 
|     #or 
,location_\K[^,]+ #Match one or more non-comma-characters after location_ 
|     #or 
,\K[^_]+(?=_text) #Match one or more non-underscore-characters that are 
        # immediately followed by _textafter button_ 

在每個條件表達式的\K裝置從該點匹配和有效地除去使用捕獲組進行這種情況下的需要。 當使用捕獲組時,preg_match_all()創建了多個子數組 - 一個填充了全部字符串匹配,並且至少還有一個捕獲值。應儘可能使用 \K,因爲它可以將陣列大小減少50%。

代碼:

$array=preg_match_all('/button_\K[^,]+|,location_\K[^,]+|,\K[^_]+(?=_text)/',$str,$out)?$out[0]:[]; 
var_export($array); 

的輸出結果相同:

array (0 => 'reset', 1 => 'text', 2 => 'email',) 
+0

我想使用preg_match() –

+0

這次不是明智的選擇。我可以製作一個,但它不是這項任務的正確功能。給我一點時間。 – mickmackusa

3

正則表達式:/\_\K[a-zA-Z0-9]+

\_\K這將匹配_\K將全部重置比賽。

2.[a-zA-Z0-9]+會匹配所有這些字符

Try this code snippet here

<?php 

ini_set('display_errors', 1); 
$str = 'button_reset,location_text,email_text'; 
preg_match_all("/\_\K[a-zA-Z0-9]+/",$str,$matches); 
print_r($matches); 

輸出:

Array 
(
    [0] => Array 
     (
      [0] => reset 
      [1] => text 
      [2] => text 
     ) 
) 
相關問題