PHP Spintax return array with all possibilities -
i have string: {hello|howdy|hola} you, {mr.|mrs.|ms.} {smith|williams|austin}
!
i wonder if can me out function return array possibilities ? or @ least provide logic on how them , php functions use ?
thank you
nested foreach
loops.
foreach($greetings greeting) foreach($titles title) foreach($names $name) echo $greeting,' you, ',$title,' ',$name;
you can adjust order appear sorting arrays beforehand , changing order on first 3 lines
update
this came using recursive function
it assumes have data in using regular expressions , explode should pretty trivial to:
$data = array( array("hello","howdy","hola"), array(" you, "), array("mr.", "mrs.", "ms."), array(" "), array("smith","williams","austin"), array("!") );
now here function
function permute(&$arr, &$res, $cur = "", $n = 0){ if ($n == count($arr)){ // past end of array... push results $res[] = $cur; } else { //permute 1 level down array foreach($arr[$n] $term){ permute($arr, $res, $cur.$term, $n+1); } } }
here example invocation:
$ret = array(); permute($data, $ret); print_r($ret);
which yields output
array ( [0] => hello you, mr. smith! [1] => hello you, mr. williams! [2] => hello you, mr. austin! [3] => hello you, mrs. smith! [4] => hello you, mrs. williams! [5] => hello you, mrs. austin! [6] => hello you, ms. smith! [7] => hello you, ms. williams! [8] => hello you, ms. austin! [9] => howdy you, mr. smith! [10] => howdy you, mr. williams! [11] => howdy you, mr. austin! [12] => howdy you, mrs. smith! [13] => howdy you, mrs. williams! [14] => howdy you, mrs. austin! [15] => howdy you, ms. smith! [16] => howdy you, ms. williams! [17] => howdy you, ms. austin! [18] => hola you, mr. smith! [19] => hola you, mr. williams! [20] => hola you, mr. austin! [21] => hola you, mrs. smith! [22] => hola you, mrs. williams! [23] => hola you, mrs. austin! [24] => hola you, ms. smith! [25] => hola you, ms. williams! [26] => hola you, ms. austin! )
Comments
Post a Comment