> suppose there's a string
> $string="I like my(hot) coffee with sugar and (milk)(PHP)";
> 
> I would like to get an output of all possible combinations of the
sentence
> with the words between brackets:
> eg.
> I like my hot coffee with sugar and
> I like my hot coffee with sugar and milk
> I like my hot coffee with sugar and milk php
> I like my coffee with sugar and
> I like my coffee with sugar and milk php
> etc.etc.
> 
> The number of the words between brackets can differ and they can occur
> everywhere. The most important is that all combinations are returned
but
> the
> sentence (not between brackets) should be there.

Here's a solution. :) Hope it helps. You could adapt it to not use the
placeholders if each word in parenthesis is unique. 

<?

$text = "I like my (hot) coffee with sugar and (milk)(PHP)";

//match words between parenthesis
preg_match_all("/\((.*)\)/U",$text,$matches);

//replace words with placeholder
//<#x#> where 'x' is incremented
//for each placeholder
$a=0;
$text2 = preg_replace("/\((.*)\)/Ue",'sprintf("<#%d#>",$a++)',$text);

//determine how many words were matched
//and what decimal number equals a binary 
//number of all ones and a length equal to
//the number of matches
$num_matches = count($matches[0]);
$dec = bindec(str_repeat("1",$num_matches));

//Original text
echo $text . "<hr>";

for($x=0;$x<=$dec;$x++)
{
    $text3 = $text2;
    $cpy = $x;
    //loop equal to the number of matched words
    for($y=0;$y<$num_matches;$y++)
    {
        //if least significant bit is one then
        //replace placeholder with word from $matches
        //otherwise an empty string
        $replace = ($cpy & 1) ? $matches[1][$y] : '';
        $text3 = str_replace("<#$y#>",$replace,$text3);
        //shift bits in $cpy one to the right
        $cpy = $cpy >> 1;
    }
    echo $text3 . "<br>";    
}
    
?>

---John W. Holmes...

PHP Architect - A monthly magazine for PHP Professionals. Get your copy
today. http://www.phparch.com/



-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to