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

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
ccromp
Forum Newbie
Posts: 2
Joined: Fri Jun 30, 2006 11:01 am

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

Post 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!
Jixxor
Forum Commoner
Posts: 46
Joined: Wed Jun 07, 2006 5:53 pm
Location: Lakeland, FL

Post 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
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post 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.
Robert Plank
Forum Contributor
Posts: 110
Joined: Sun Dec 26, 2004 9:04 pm
Contact:

Post 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)];
}

?>
ccromp
Forum Newbie
Posts: 2
Joined: Fri Jun 30, 2006 11:01 am

Thanks a TON!!

Post by ccromp »

Thanks a ton, Robert Plank! That solution works amazingly!
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Sweet little function dude.
Post Reply