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!
How do I replace a string with an array inside a string?
Moderator: General Moderators
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.
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.
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
-
Robert Plank
- Forum Contributor
- Posts: 110
- Joined: Sun Dec 26, 2004 9:04 pm
- Contact:
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!!
Thanks a ton, Robert Plank! That solution works amazingly!
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA