Alex
Alex

Reputation: 87

Regular Expression to get strings enclosed in braces

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?

Upvotes: 1

Views: 1455

Answers (3)

rubber boots
rubber boots

Reputation: 15184

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

Upvotes: 3

gen_Eric
gen_Eric

Reputation: 227200

$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

Upvotes: 0

ircmaxell
ircmaxell

Reputation: 165191

You could try:

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

Upvotes: 0

Related Questions