t_machine Posted November 29, 2007 Share Posted November 29, 2007 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 Quote Link to comment https://forums.phpfreaks.com/topic/79451-solved-how-to-replace-words-in-string-with-values-from-associate-array/ Share on other sites More sharing options...
kenrbnsn Posted November 29, 2007 Share Posted November 29, 2007 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 Quote Link to comment https://forums.phpfreaks.com/topic/79451-solved-how-to-replace-words-in-string-with-values-from-associate-array/#findComment-402268 Share on other sites More sharing options...
t_machine Posted November 29, 2007 Author Share Posted November 29, 2007 Thank you very much for your prompt reply. It works perfectly Quote Link to comment https://forums.phpfreaks.com/topic/79451-solved-how-to-replace-words-in-string-with-values-from-associate-array/#findComment-402282 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.