I am trying to parse a string. The catch is each of the variables in the string may occur more than once, and I need to replace each repeated occurrence with a unique replacement.
example $string = "$Pronoun $Adjective $Noun is as $Adjective as an $Adjective $Noun"
I’ve tried str_replace("$Pronoun", getRandomWordByType('Pronoun'), $string)
This works apart from the fact that each occurrence of “$Pronoun” gets replaced with the same pronoun retrieved from a single call to my getRandomWordByType('Pronoun') method.
My objective is to build interesting sentences dynamically, replacing placeholders with words retrieved from a database of words, that are categorised by type…
Thanks in advance for any suggestions 🙂
Try this:
This will automatically convert any keyword of the form
$Somethingby passingSomethingto thegetRandomWordByTypefunction. Another advantage is that the random word function is called once for each word.To prevent accidental replacements, for example
$NotAKeyword, havegetRandomWordByTypereturn'$'.$keyword(where$keywordis the function’s argument) if it can’t find the keyword in the valid list.