Page 1 of 1

How do I replace a string with an array inside a string?

Posted: Fri Jun 30, 2006 11:23 am
by ccromp
If the subject line confused you, here's what I want to do:

I've got a string such as the following:
"Hello, my name is #Chris/Frank/John#, what is your name?"

I want to take what is inside the number signs (Chris/Frank/John), put it into an array and then pick a random choice from the list. The final result would be one of the following, chosen randomly:

"Hello, my name is Chris, what is your name?"
"Hello, my name is Frank, what is your name?"
"Hello, my name is John, what is your name?"

I know how to pick a random indexs from an array, I just don't know how to pull an array out of a string. Is is possible to insert a function directly into a string such as:

"Hello, my name is chooseOption(array("Chris","Frank","John")), what is your name?"

Thanks for your help!

Posted: Fri Jun 30, 2006 11:28 am
by Jixxor
Intially you'll need a regex function to pull the names and place them in an array, probably preg_match() or preg_match_all()

You can then use the returned array and print the names as you like using a for() or foreach() statement.

As I'm still learning regex, I can't really help you in that department. :P

Posted: Fri Jun 30, 2006 11:34 am
by RobertGonzalez
You are going to have to regex the string for what is between the octothorps (#), then use explode() to separate the string on the '/' character. Voila, you have your array.

Posted: Fri Jun 30, 2006 11:40 am
by Robert Plank

Code: Select all

<?php

$string = "Hello, my name is #Chris/Frank/John#, what is your name?";

$result = preg_replace_callback('/#(.*?)#/', 'randomSlash', $string);
echo $result;

function randomSlash($input) {
   $parts = explode('/', $input[1]);
   return $parts[array_rand($parts)];
}

?>

Thanks a TON!!

Posted: Fri Jun 30, 2006 11:48 am
by ccromp
Thanks a ton, Robert Plank! That solution works amazingly!

Posted: Fri Jun 30, 2006 12:26 pm
by RobertGonzalez
Sweet little function dude.