tags:

views:

36

answers:

2

Hi All,

I have a string that contains several "placeholders" in it, and each placeholder is marked with this syntax: {value}.

I want to be able to pull out each placeholder within the string and load them into an array.

For example, if I had this string here... "this is a {test} string, to demonstrate my {objective}."

I would want the end result to be an array that contained two values, "test" and "objective".

I poked around with preg_split but couldn't quite wrap my head around it. Any ideas on how to make this happen?

Thanks!

+1  A: 

I think you can use this

preg_match_all('/\{([^\}]+)\}/i', $your_string, $match);

all the placeholders in $match[1]; Read more about that function at http://php.net/manual/en/function.preg-match-all.php

Bang Dao
+1  A: 

You can try the following to get what you need:

$placeHolders = array();
if(preg_match_all('/\{([^{}}]+)\}/', $haystack, $matches)) {
    $placeHolders = $matches[1];
}

Since you didn't specifically state what would be allowed in a place holder, I kept the regular expression quite generic. Basically, a placeholder would be anything inside curly braces (except for curly braces themselves).

You might want to restrict more, such as alphanumeric characters only. In this case try:

'/\{([a-zA-Z0-9]+)\}/'

Edit: a resource for regular expressions: http://www.regular-expressions.info/reference.html

Guillaume Bodi