1

I know the title is similar to other questions but I cannot find what I'm looking for.

I have a variable, say:

$myVar = 'bottle';

And, then I have a string:

$myString = 'Hello this is my string';

I need some code to select a random word the $myString and replace it with $myVar. How can I do this?

5 Answers 5

6

Nothing like a good old-fashioned PHP race:

$myString = 'Hello this is my string';
$myVar = 'bottle';

$words = explode(' ', $myString);      // split the string into words    
$index = rand(0, count($words) - 1);   // select a random index    
$words[$index] = $myVar;               // replace the word at the random position
$myString = implode(' ', $words);      // merge the string back together from the words   

You could also do this using regular expressions:

$idx = rand(0, str_word_count($myString) - 1);
$myString = preg_replace("/((?:\s*\w+){".$idx."})(?:\s*\w+)(.*)/", 
                         "\${1} $myVar\${2}", $myString);

This skips forward a random number of words and replaces the next word.

You can see this regex in action here. Changing the number inside the curly braces causes the first capture group to consume more words.

Sign up to request clarification or add additional context in comments.

Comments

2

You could just count the number of word separators (spaces in this case) and user rand to get random one of them, then just get the content of that word by strpos with rand value offset (third parameter) or just explode the string to array (by space) and then implode again (with space again) to string after replacing random word.

Comments

2

It is what you need:

$myVar = 'bottle';
$myString = 'Hello this is my string';
$myStringArray = explode(' ', $myString);

$rand = mt_rand(0, count($myStringArray)-1);
$myStringArray[$rand] = $myVar;

$myNewString = implode(' ', $myStringArray);

Comments

2

Well how about this:

$words = explode(' ', $myString );
$wordToChange = rand(0, count($words)-1);
$words[$wordToChange] = $myVar;
$final = implode(' ', $words)

1 Comment

You explode the wrong var. $myVar is the replacement
1
$myVar = "bottle";
$myString = 'Hello this is my string';

$words = explode(" ", $myString);
$words[rand(0, count($words)-1)] = $myVar;
echo join(" ", $words);

Comments

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.