I’m working with an API that returns text in the following format:
{I want|I need} to make this {stupid|awesome|irritating} sentence
{formatting {rapidly|quickly} and random|spin and be random}
Using PHP, I need to format the string like:
"I need to make this irritating sentence formatting quickly";
OR
"I want to make this awesome sentence spin and be random";
from the initial text.
I would have no problem if the curly brackets couldn’t contain another set of curly brackets. Any advice or any piece of code that could help me solve this problem?
I assumed your source string is like this:
otherwise the brackets are nested and your output example does not match how you put them in source string. Then use
preg_match_all()like this:which for your
$sourceStringwould produce:And you get all items. Then you can process each entry, strip “{” and “}”,
explode()on “|” to get array of options to choose from. Then you pick what you want and replace formerly found item with it. Note, I capture offset where matching pattern is found, because you cannot just eventually dostr_replace()because I assume you want to be able to use the same entry in many places (i.e. “{this|that} foo {this|that}”.str_replace()would replace both while I think it is not desired. So we got offset in the string, length of string can be easily computed but this is sufficient to do some surgery, and cut off our entry and put replacement. Other, cleaner approach is to use preg_replace_callback() and put all that “logic” in the callback so you could do whole processing in one pass.