...

View Full Version : String manipulations



b_hole
04-01-2007, 08:42 AM
Hi,

I get a string from a form, and I need to manipulate it, and create an array containing all the results.

- If the string has 1 word, the array should contain 1 element with the same word.
- If the string has 2 words, the array should contain 2 elements, looking like this: [0] => "word1word2", [1] => "word1-word2"
- If the string has 3 words, the array should contain 4 elements, looking like this:
[0] => "word1word2word3", [1] => "word1-word2word3", [2] => "word1word2-word3", [3] => "word1-word2-word3"
- If the string has 4 words, the array should contain 8 elements, looking like this:
[0] => "word1word2word3word4", [1] => "word1-word2word3word4", [2] => "word1word2-word3word4", [3] => "word1word2word3-word4", [4] => "word1-word2-word3word4", [5] => "word1-word2word3-word4", [6] => "word1word2-word3-word4", [7] => "word1-word2-word3-word4"
- etc.

Hope you get the point...
I'm trying to figure out a to handle this, buy I can't think of how to do it.
What do you guys think? Any help would be appreciated.

Thanks.

dumpfi
04-01-2007, 03:02 PM
Try this:
<?php
function doIt($str)
{
$words = preg_split('#\s+#', $str); // split the string at spaces to get a word array
$lastWord = array_pop($words); // the last word needs special handling because it does never get a `-` appended
$wordArr = array('');
for($i = 0, $count = count($words); $i < $count; ++$i)
{
$wordArr = array_merge($wordArr, $wordArr); // double the size of the array for each word and use what we've already constructed
foreach($wordArr as $key => $wordStr)
{
if($key < (1<<$i)) // to append or not to append - that's the question
{
$wordArr[$key] .= $words[$i];
}
else
{
$wordArr[$key] .= $words[$i].'-';
}
}
}
foreach($wordArr as &$wordStr) // append the last word to all strings
{
$wordStr .= $lastWord;
}
return $wordArr;
}
print_r(doIt('word1 word2 word3 word4'));
?>dumpfi

iLLin
04-01-2007, 03:25 PM
Must be a php5 thang, but I had to change that lastword part. This worked for me.


function doIt($str)
{
$words = preg_split('#\s+#', $str); // split the string at spaces to get a word array
$lastWord = array_pop($words); // the last word needs special handling because it does never get a `-` appended
$wordArr = array('');
for($i = 0, $count = count($words); $i < $count; ++$i)
{
$wordArr = array_merge($wordArr, $wordArr); // double the size of the array for each word and use what we've already constructed
foreach($wordArr as $key => $wordStr)
{
if($key < (1<<$i)) // to append or not to append - that's the question
{
$wordArr[$key] .= $words[$i];
}
else
{
$wordArr[$key] .= $words[$i].'-';
}
}
}
foreach($wordArr as $wordStr) // append the last word to all strings
{
$final_words[] .= $wordStr.$lastWord;
}
return $final_words;
}

b_hole
04-04-2007, 01:49 PM
dumpfi - thanks a lot, works like a charm :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum