2013-02-28 60 views
2

我有一個像{ASK(Value, Value, 'Sentence', Some_Char)}這樣的字符串,我需要獲取()中的爆炸值。我做錯了什麼?用正則表達式爆炸

preg_match_all('/\{ASK\((.*?),\)\}/', '{ASK(Value, Value, \'Sentence\', X)}', $matches); 
print_r($matches); 
+0

好吧,在{{值(Value,Value,'Sentence',Some_Char)}''結束於',)}',所以你什麼都不匹配 – 2013-02-28 07:32:56

+0

什麼是字符串的格式?一個例子不會削減它。我可以編寫一個適用於此示例的正則表達式,但未來可能會失敗。 – nhahtdh 2013-02-28 07:33:37

+0

@JanDvorak據我瞭解'(。*?),'應該每次搜索直到','或者我錯了? – Kin 2013-02-28 07:34:43

回答

0

從正則表達式中取出逗號,並匹配。

preg_match_all('/\{ASK\((.*?)\)\}/', '{ASK(Value, Value, \'Sentence\', X)}', $matches); 
print_r($matches); 

//Explode the matched group 
$exploded = explode(',',$matches[1]); 
print_r($exploded); 

/* 
* Note that we used $matches[1] instead of $matches[0], 
* since the first element contains the entire matched 
* expression, and each subsequent element contains the matching groups. 
*/ 
0
$s = "{ASK(Value, Value, 'Sentence', Some_Char)}"; 
$p = '#\{ASK\((.*?)\)\}#'; 
preg_match_all($p, $s, $matches); 
print_r($matches); 
0

,只需拆分&爆炸

$Myval = "{ASK(Value, Value, 'Sentence', Some_Char)}"; 

$splitedVal = split('[()]', $Myval); 

$explodedVal = explode(",", $splitedVal[1]); 

print_r($explodedVal); 

//輸出

Array ([0] => Value [1] => Value [2] => 'Sentence' [3] => Some_Char) 
0

一個簡單的方法來做到這一點(雖然不是正則表達式中完全包含)可能是:

preg_match_all('/\{ASK\([^)]*\)\}/', '{ASK(Value, Value, \'Sentence\', X)}', $matches); 
$values = explode($matches[1]); 
0

只要你ValuesSentencesChars不包含,),這種單一的正則表達式模式將提供無需額外explode()電話。

圖樣:~(?:\G, |ASK\()\K[^,)]+~Pattern Demo

代碼:(Demo

$string="{ASK(Value, Value, 'Sentence', Some_Char)}"; 

print_r(preg_match_all('~(?:\G, |ASK\()\K[^,)]+~',$string,$out)?$out[0]:[]); 

輸出:

Array 
(
    [0] => Value 
    [1] => Value 
    [2] => 'Sentence' 
    [3] => Some_Char 
) 

「神奇」 是在\G。這告訴正則表達式在字符串的開頭或者在上一次匹配之後繼續匹配。這裏有一個類似的回答,我發佈了:https://stackoverflow.com/a/48373347/2943403

相關問題