1

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!

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.