0

I have the 2 variables/strings below:

$article = ('Perfume is a mixture of fragrant word1 and aroma complexes, which can be applied to the human body, animals, word2, objects, and living spaces in order to give off a pleasant word3.');

$words = '{word1|word2|word3|word4|word5}';

What I need to do is to search $article for any words in $word and if found randomly replace the word found in $article with a random picked word from $word.

How can I do that please?

4
  • Use array, so randomly pick a value from it. Commented Sep 12, 2013 at 10:16
  • $words has to be in the current format Commented Sep 12, 2013 at 10:16
  • $words need to be array instead of string Commented Sep 12, 2013 at 10:17
  • leave it this way and explode() it to create a dynamic array, this way you won't disturb $words format. You can also use array_rand(explode("|", $words)) Commented Sep 12, 2013 at 10:18

2 Answers 2

3

If you need to keep everything in the same format;

$article = ('Perfume is a mixture of fragrant word1 and aroma complexes, which can be applied to the human body, animals, word2, objects, and living spaces in order to give off a pleasant word3.');
$words = '{word1|word2|word3|word4|word5}';

$words = explode('|', str_replace(array('{', '}'), '', $words));

echo str_replace($words, $words[array_rand($words)], $article);
Sign up to request clarification or add additional context in comments.

Comments

0

Create an array of $words. Get a random key of the array and str_replace the $article with the randomly chosen words.

$words = array('word1', 'word2', 'word3', 'word4');
$randkeyA = array_rand($words);
$randkeyB = array_rand($words);
echo str_replace($words[$randkeyA], $words[$randkeyB], $article);

3 Comments

This doesn't work, because you're replacing $words[$randkey] with $words[$randkey], so replacing the same word with itself
Lol, you're right, editted my piece of code. It's still possible this way though the word is replaced by the same word. Your answer is better :)
Sorted ;) However, the OP says "$words has to be in the current format"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.