views:

396

answers:

5

How can I iteratively create a variant of "Murrays" that has an apostrophe after each letter? The end-result should be:

"m'rrays,mu'rrays,mur'rays,murr'ays,murra'ys,murray's"
+1  A: 

You want to iterate through the name, and re-print it with apostrophe's? Try the following:

<?php

    $string = "murrays";

    $array  = str_split($string);
    $length = count($array);
    $output = "";

    for ($i = 0; $i < $length; $i++) {
      for($j = 0; $j < $length; $j++) {
        $output .= $array[$j];
     if ($j == $i) 
      $output.= "'";
      }
      if ($i < ($length - 1))
       $output .= ",";
    }

    print $output;

?>
Jonathan Sampson
i want to make this type of differnt string like m'urrays,mu'rrays,mur'rays,murr'ays,murra'ys,murray's,murrays' so how to make this type of string using php pl help
mehul
Shame on you posting this outside of a comment, Sampson.
Welbog
Fixed, Welbog.
Jonathan Sampson
Removed my -1
Welbog
Don’t use `count` in your looping condition if the size of the array doesn’t change. Better define a variable that holds that value.
Gumbo
Thanks Gumbo.
Jonathan Sampson
+1  A: 

My suggestion:

<?php                      
function generate($str, $add, $separator = ',')
{
    $split = str_split($str);
    $total = count($split) - 1;

    $new = '';
    for ($i = 0; $i < $total; $i++)
    {
        $aux = $split;
        $aux[$i+1] = "'" . $aux[$i+1];
        $new .= implode('', $aux).$separator;
    }
    return $new;
}
echo generate('murrays', "'");
?>
inakiabt
A: 

Here’s another solution:

$str = 'murrays';
$variants = array();
$head = '';
$tail = $str;
for ($i=1, $n=strlen($str); $i<$n; $i++) {
    $head .= $tail[0];
    $tail = substr($tail, 1);
    $variants[] = $head . "'" . $tail;
}
var_dump(implode(',', $variants));
Gumbo
A: 

well that's why functionnal programming is here

this code works on OCAML and F#, you can easily make it running on C#

let generate str =
     let rec gen_aux s index =
         match index with
             | String.length s -> [s]
             | _ -> let part1 = String.substr s 0 index in
                    let part2 = String.substr s index (String.length s) in
                    (part1 ^ "'" ^ part2)::gen_aux s (index + 1)
     in gen_aux str 1;;

generate "murrays";;

this code returns the original word as the end of the list, you can workaround that :)

martani_net
sorry folks I didn't pay attention to the php tag!
martani_net
A: 

Here you go:

$array = array_fill(0, strlen($string) - 1, $string);
implode(',', array_map(create_function('$string, $pos', 'return substr_replace($string, "\'", $pos + 1, 0);'), $array, array_keys($array)));
soulmerge
waw is there an map function for arrays in php??? that's totally awesome
martani_net