I have a string: {Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Austin}
!
I wonder if someone can help me out with a function that will return an array with all the possibilities ? Or at least provide the logic on how to get them and what PHP functions to use ?
Thank you
Nested foreach
loops.
foreach($greetings as greeting)
foreach($titles as title)
foreach($names as $name)
echo $greeting,' to you, ',$title,' ',$name;
You can adjust the order that they appear by sorting the arrays beforehand and by changing the order on the first three lines
UPDATE
This is what I came up with using a recursive function
It assumes you have your data in something like this using regular expressions and explode this should be pretty trivial to get to:
$data = array(
array("Hello","Howdy","Hola"),
array(" to you, "),
array("Mr.", "Mrs.", "Ms."),
array(" "),
array("Smith","Williams","Austin"),
array("!")
);
Now here is the function
function permute(&$arr, &$res, $cur = "", $n = 0){
if ($n == count($arr)){
// we are past the end of the array... push the results
$res[] = $cur;
} else {
//permute one level down the array
foreach($arr[$n] as $term){
permute($arr, $res, $cur.$term, $n+1);
}
}
}
Here is an example invocation:
$ret = array();
permute($data, $ret);
print_r($ret);
Which yields the output
Array
(
[0] => Hello to you, Mr. Smith!
[1] => Hello to you, Mr. Williams!
[2] => Hello to you, Mr. Austin!
[3] => Hello to you, Mrs. Smith!
[4] => Hello to you, Mrs. Williams!
[5] => Hello to you, Mrs. Austin!
[6] => Hello to you, Ms. Smith!
[7] => Hello to you, Ms. Williams!
[8] => Hello to you, Ms. Austin!
[9] => Howdy to you, Mr. Smith!
[10] => Howdy to you, Mr. Williams!
[11] => Howdy to you, Mr. Austin!
[12] => Howdy to you, Mrs. Smith!
[13] => Howdy to you, Mrs. Williams!
[14] => Howdy to you, Mrs. Austin!
[15] => Howdy to you, Ms. Smith!
[16] => Howdy to you, Ms. Williams!
[17] => Howdy to you, Ms. Austin!
[18] => Hola to you, Mr. Smith!
[19] => Hola to you, Mr. Williams!
[20] => Hola to you, Mr. Austin!
[21] => Hola to you, Mrs. Smith!
[22] => Hola to you, Mrs. Williams!
[23] => Hola to you, Mrs. Austin!
[24] => Hola to you, Ms. Smith!
[25] => Hola to you, Ms. Williams!
[26] => Hola to you, Ms. Austin!
)