我有一个像{ASK(Value, Value, 'Sentence', Some_Char)}
这样的字符串,我需要在()
中获得爆炸值。我做错了什么?
preg_match_all('/\{ASK\((.*?),\)\}/', '{ASK(Value, Value, \'Sentence\', X)}', $matches);
print_r($matches);
答案 0 :(得分: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.
*/
答案 1 :(得分:0)
$s = "{ASK(Value, Value, 'Sentence', Some_Char)}";
$p = '#\{ASK\((.*?)\)\}#';
preg_match_all($p, $s, $matches);
print_r($matches);
答案 2 :(得分: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 )
答案 3 :(得分:0)
执行此操作的简单方法(尽管未完全包含在正则表达式中)可能是:
preg_match_all('/\{ASK\([^)]*\)\}/', '{ASK(Value, Value, \'Sentence\', X)}', $matches);
$values = explode($matches[1]);
答案 4 :(得分:0)
只要您的Values
,Sentences
和Chars
不包含,
或)
,那么此单一正则表达式模式将无需额外提供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