Jump to content

[SOLVED] How to replace words in string with values from associate array?


t_machine

Recommended Posts

Hi, I am wondering if this is possible. The following example will demonstrate what I would like to achieve.

 

Example:

 

$myarray = array("text1"=>"apples", "text2"=>"banana", "text3"=>"pineapple");

 

$mystring = 'I like eating text1 but text3 is my favorite.';

 

 

//result

I like eating apples but pineapple is my favorite.

 

How can I achieve the result using the array and string.

 

Thanks for any help :)

You can do something like:

<?php
$myarray = array("text1"=>"apples", "text2"=>"banana", "text3"=>"pineapple");
$mystring = 'I like eating text1 but text3 is my favorite.';
echo $mystring . '<br>';
foreach ($myarray as $k => $v)
    $mystring = str_replace($k,$v,$mystring);
echo $mystring . '<br>';
?>

 

Ken

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.