Page 1 of 1

Need help with a small PHP project

Posted: Mon Dec 13, 2010 5:51 pm
by mikeglover
I wish to create a php application which takes an array of set charaters eg. ! £ $ % ^ & and randomly places them infront of every word in a sentence.

So "This is an example" ... would become "£This !is $an ^example"

I have already found an article that explains adding characters http://www.canbal.com/view.php?sessioni ... 2BqRbak%3D

And so far have the basics of:

Code: Select all

$my_array = array("!", "£", "$", "%", "^", "&");
$str = 'This is an example of a sentence';
$str = $random . implode(' ' . $random ,explode(' ',$str));
The bit i'm stuck on is trying to get insert the random characters.

Would appreciate any help :)

Re: Need help with a small PHP project

Posted: Mon Dec 13, 2010 7:05 pm
by Jonah Bron

Code: Select all

$my_array = array("!", "£", "$", "%", "^", "&");
$str = 'This is an example of a sentence';
$str = explode(' ', $str);

foreach ($str as &$word) {
    $word = $my_array[array_rand($my_array)] . $word;
}

$str = implode(' ', $str);
As you can see, this code uses array_rand() (http://php.net/array-rand). Also, notice the & symbol in the loop: that means that the element of the array should be passed by reference. Otherwise, this script would not change the string.