开发者

Regular Expression to get strings enclosed in braces

开发者 https://www.devze.com 2023-01-11 08:31 出处:网络
I开发者_如何学运维 want to get an array of the following types of strings: data {string1} {string2} {string3} data

I开发者_如何学运维 want to get an array of the following types of strings:

data {string1} {string2} {string3} data

I want to get an array whose values are string1/string2/strin3. How can I do this?


one-liner w/o capturing parentheses, the string resides in $stuff:

$arr = preg_match_all('/(?<={)[^}]+(?=})/', $stuff, $m) ? $m[0] : Array();

result:

foreach($arr as $a) echo "$a\n";

string1
string2
string3

Regards

rbo


You could try:

$data = '';
$matches = array();
if (preg_match_all('#\\{([^}]*)\\}#', $string, $matches, PREG_PATTERN_ORDER)) {
    $data = implode('/', $matches[1]);
}
echo $data;


$str = "data {string1} {string2} {string3} data";
preg_match_all('/{\w*}/',$str, $matches);
echo $matches[0][0]; // {string1}
echo $matches[0][1]; // {string2}
echo $matches[0][2]; // {string3}

PHP preg_match_all

0

精彩评论

暂无评论...
验证码 换一张
取 消