Need help with a small PHP project

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mikeglover
Forum Newbie
Posts: 1
Joined: Mon Dec 13, 2010 5:36 pm

Need help with a small PHP project

Post 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 :)
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Need help with a small PHP project

Post 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.
Post Reply