Parsing String and Recombining Variations

Okay, let’s see if I can explain this clearly.

I want to input a string that would be in the form of

Please [show/teach] me how to figure this (damn/crazy) thing out.

Then output a series of sentences with every different combination of word choices in the brackets and parenthesis. Words in brackets are mandatory, words in parenthesis are optional.

For example, the above should output:

Please show me how to figure this thing out.
Please show me how to figure this crazy thing out.
Please show me how to figure this damn thing out.
Please teach me how to figure this thing out.

Etcetera…

The order of the outputted sentences does not matter.

The optionals will sometimes only have one choice, so a word will either be there, or not be there.

Options must support any number of choices, not just two.

There may be multiple choices in different locations through the sentence.

In other words “[Please/Kindly] [show/teach/educate] me how to figure this (damn/crazy) thing out (before I go mad).” needs to be workable.

Nesting options inside of options would be awesome, but isn’t mandatory.

There, that is what I need. To obtain that, I need
a) an existing free script that will do this all ready, or with minor modification.
b) someone so awesome with PHP they can write out the code for me in a minute off the top of their head
c) a point in a solid right direction. Preferably something more useful than just “try explode()”

Thanks for your help.

You will want to retrieve from the string all of the mandatory words. preg_match_all can do that, so you would use it once to find all of the mandatory terms, and another time for all of the optional terms.

You’ll want to wind up with an array of mandetory terms

array(
    0 => 'show/teach'
)

which would contain other numerically indexed entries if other groups of mandetory terms appear in the source text.

You will also have a similar array of optional terms.

Then, you just need to loop through them, split each of the terms by the slash, and loop through each of those, not forgetting that the optional ones require an extra time with no term.

You may want to create a function that can accept the string, and the terms that you want to loop through variations of, which could use a loop combined with preg_replace to create the different variations and return them as an array of different variations of the string.