views:

54

answers:

2

Hi all,

I'm trying to find all possible combinations of a word, and have certain letters replaced.

So, I have the following code:

<form name="search" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="searchterm" />
<input type="submit" value="Submit"/>
</form>

<?php


function pset($array) {
    $results = array(array());

    foreach ($array as $element)
        foreach ($results as $combination)
            array_push($results, array_merge(array($element), $combination));

    return $results;

}


$searchterm = $_POST["searchterm"];

$search  = array(
                    array("t","7"),
                    array("e","3")
                );



$searchpowerset=pset($search);                 

foreach($searchpowerset as $a)
{
    $newterm = str_replace($a[0][0],$a[0][1],$searchterm);
    echo $newterm . "<br/>";
}


?>

The input for this from the form would be: peter

I would expect the output to include:

p3t3r
p373r

At the moment it's returning:

peter
pe7er
p3t3r
p3t3r

The repetitons aren't an issue as I can get rid of those easily, but I need to be able to have all replacements work on each cycle through.

Thanks in advance.

A: 

Your code substitutes every instance of a character in the string, so it can't really work.

My implementation:

$searchterm = $_POST['searchterm'];

$search = array( array('e', '3'), array('t', '7'), array('e', 'E') );

function replace($string, $prefix = '')
{
    global $search;
    $result = array();
    if(!$string) return array($prefix);
    $letter = substr($string, 0, 1);
    $rest   = substr($string,1);

    $result = array_merge($result, replace($rest, $prefix . $letter));
    foreach($search as $term) {
        if($term[0] == $letter) {
            $result = array_merge($result, replace($rest, $prefix . $term[1]));
        }
    }

    return $result;
}

var_dump(replace($searchterm));
Mewp
You sir, are a genius! :)
fdf33
A: 

HI Mewp,

Your answer works really well. Could you explain what's going on at each step though?

thx