Jump to content

Weird preg_replace / match


jaymc

Recommended Posts

The best thing I can do to explain what I want is to give you some sort of example. Look below

 

<?

$array['price'] = 415;
$array['color'] = "red";
$array['computer'] = "linux";

$startString = "I have a #color# #computer# computer that cost me #price# pounds";

// What I want
$endString = "I have a red linux computer that cost me 415 pounds";
?>

 

Points:

The array key names could be anything e.g $array['sdfgdfhdasgadsfhg'] however if #sdfgdfhdasgadsfhg# is found it will replace #sdfgdfhdasgadsfhg# with what ever the value of $array['sdfgdfhdasgadsfhg']

 

 

So basically, find occurances of #*# where * could be anything. Check if the value in between #*# is a keyname of $array, if it is replace #*# with $array[*]

 

So

$array['food'] = "Pizza";

$string = "I love #food# I eat it all the time";

 

Becomes

$string = "I love Pizza I eat it all the time";

 

 

Fire away!

Link to comment
https://forums.phpfreaks.com/topic/171802-weird-preg_replace-match/
Share on other sites

Ok I came up with this

 

		$array['name'] = "Jamie";
	$array['month'] = "January";


	$string = "#name# how are you on #month# you good?";
	preg_match_all('/#(.*?)#/', $string, $match);


	foreach ($match[1] as $data) {
		$string = str_replace("#$data#", $array[$data], $string);
	}

	echo $string;

 

Anything better?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.