-4

I have a string: "This is a [boy/girl] in a [house/car] I want split it into 4 strings:

  1. This is a boy in a house
  2. This is a girl in a house
  3. This is a boy in a car
  4. This is a girl in a car

How can I do that? Thanks.

  • I don't see any PHP code in your question. – EternalHour Oct 15 '14 at 04:06
  • What you're looking for is called "permutations". You'd need a loop or recursive function after preferrably regex-matching the alternatives in square brackets. – mario Oct 15 '14 at 04:07
  • See also [Need algorithm to make simple program (sentence permutations)](http://stackoverflow.com/q/5613089) for the approach. (There's also a PHP example somewhere.. Use the search if you just came for copy+pasting.) – mario Oct 15 '14 at 04:11
  • I want a solution for this. not code. thanks. – Anh Tran Oct 15 '14 at 06:42

1 Answers1

1

I hope this will help you

$string = 'This is a [boy/girl] in a [house/car]';
preg_match_all('/\[(.+?)\]/', $string, $matches);
$find_array = $matches[0];
foreach($matches[1] as $row) {
    $replace_array[] = explode("/", $row);
}

$output[] = str_replace($find_array,array($replace_array[0][0],$replace_array[1][0]),$string);
$output[] = str_replace($find_array,array($replace_array[0][1],$replace_array[1][0]),$string);
$output[] = str_replace($find_array,array($replace_array[0][0],$replace_array[1][1]),$string);
$output[] = str_replace($find_array,array($replace_array[0][1],$replace_array[1][1]),$string);

print_r($output);

//output

[0] => This is a boy in a house
[1] => This is a girl in a house
[2] => This is a boy in a car
[3] => This is a girl in a car
noufalcep
  • 3,446
  • 15
  • 33
  • 51
  • thank you very very much. I'm looking for global case so I need loops but I don't know how many step for loop. (sorry for my English) – Anh Tran Oct 15 '14 at 07:03