Connecting Tech Pros Worldwide Forums | Help | Site Map

How do you get PHP to print this...

Newbie
 
Join Date: Mar 2007
Posts: 11
#1: Jun 24 '08
I am starting with a string. Let's say that string is "horse.gallup." Now I need to print out every variation of horse without one if its letters plus the ending ".gallup". So the result should be as follows.

orse.gallup
hrse.gallup
hose.gallup
hore.gallup
hors.gallup

Now if someone could figure out how to get the above results with any string that contains a period within it, that would be awesome.

Thanks in advance for any help. I is really appreciated.

Sincerely,
Ryan

hsriat's Avatar
Expert
 
Join Date: Jan 2008
Location: Bath, UK
Posts: 1,609
#2: Jun 24 '08

re: How do you get PHP to print this...


See if this suits your needs...
[PHP]<?php

$input = "horse.gallup";

$prefix = strtok($input, ".");
$suffix = strtok(".");

for ($i = strlen($prefix); $i>0; $i--)
{
$new_prefix = make_new_combinations($prefix, $i);

foreach($new_prefix as $key=>$value)
$new_suffix[$key] = $value.".".$suffix;

echo "<pre>";
print_r($new_suffix);

unset($new_suffix);
}

function make_new_combinations($word, $length)
{
$word_array = str_split($word);
$new_words = array();

$flags_array = get_combination_flags(count($word_array), $length);
foreach ($flags_array as $flags)
{

foreach ($flags as $key=>$flag)
if ($flag == 0)
unset($word_array[$key]);

array_push($new_words, implode("", $word_array));

$word_array = str_split($word);
}
return $new_words;
}


function get_combination_flags($total, $required)
{
$flag_array = array();
$bin = "";

for ($i=0; $i<$total; $i++)
$bin .= "1";
$dec = bindec($bin);

for ($i=0; $i<=$dec; $i++)
{
$num_of_chars = count_chars(decbin($i), 1);
if ($num_of_chars[49]==$required)
{
$temp = decbin($i);
$length = strlen($temp);
$pre = "";

if ($length<$total)
for ($j=$length; $j<$total; $j++)
$pre .= "0";

$temp = $pre.$temp;
array_push($flag_array, str_split($temp));
}
}
return $flag_array;
}
?>[/PHP]
Newbie
 
Join Date: Jun 2008
Posts: 25
#3: Jun 24 '08

re: How do you get PHP to print this...


Another code for your weird problem:

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $input = 'horse.gallup';
  3.  
  4. preg_match("/^([\w]+).([\w]+)$/", $input, $matches);
  5.  
  6. $prefix = $matches[1];
  7. $suffix = $matches[2];
  8.  
  9. for ($i = 0 ; $i < strlen($prefix) ; $i++) {
  10.     $a = substr($prefix, 0, $i);
  11.     $b = substr($prefix, $i+1, strlen($prefix));
  12.  
  13.     $text = "$a$b.$suffix";
  14.     print "$text<br>";
  15. }
  16. ?>
  17.  
Newbie
 
Join Date: Mar 2007
Posts: 11
#4: Jun 24 '08

re: How do you get PHP to print this...


Thank you so much. That worked great.
dlite922's Avatar
Expert
 
Join Date: Dec 2007
Location: Moon, Dark Side
Posts: 1,095
#5: Jun 25 '08

re: How do you get PHP to print this...


Quote:

Originally Posted by lazukars

Thank you so much. That worked great.

who's solution worked or are you referring to?
Reply