Web Hosting Talk







View Full Version : PHP Script for Combining Words


Corey Bryant
12-07-2004, 09:17 AM
I had a client that is looking for a PHP script that outputs words separately & in combination:

For example lets say i have the following words in a text file..

Cat
Dog
Fish

I would paste them into the script and it would then output something like this..

Cat
Dog
Fish
CatDog
CatFish
DogCar
DogFish
FishCat
FishDog

Of course I know about all the script site but trying to even figure out what to search for, I am at a loss.

Thanks!

cguimont
12-07-2004, 09:43 AM
Well, this would be a pretty complicated script.
First thing would be to put them into an array.
First, you need a Loop that will pass them 1 by 1.
THen a loop that will pass all the word, and have another loop in the second loop that passes all the words and stick them with the first one.

gogocode
12-07-2004, 11:01 AM
$wordsarray = array('cat', 'dog', 'fish');
for($x = 0; $x<count($wordsarray);$x++) { echo $wordsarray[$x]."\n"; for($y = 0; $y < count($wordsarray);$y++){echo $wordsarray[$x] . $wordsarray[$y]."\n";}}

Corey Bryant
12-07-2004, 11:11 AM
Thanks! I'l keep that in mind. Sonicgroup gave me this code & with a few tweaks - it seems to work:
// Text file containing words
$txt = '/path/to/wordfile.txt';

$handle = fopen($txt, 'r');

if (!$handle) {
die('Could not open...');
}

// set up arrays for storing words and concatenated words
$words = array();
$cwords = array();

// get the words
while (!feof($handle)) {
// strip_newlines is not a real function - needs to be implemented
array_push($words, strip_newlines(fgets($handle)));
}

// while we still have words
for ($i = 0; $i < count($words); $i++) {
// get the current word
$curword = $words[$i];
// loop over the words
foreach ($words as $word) {
// if the word is the same as the current word, skip it - i.e. no CatCat
if ($word == $curword) {
continue;
}
// append the concatenated word to the array
array_push($cwords, $curword.$word);
}
}

foreach ($words as $var) echo $var."";
foreach ($cwords as $var2) echo $var2."";