Z33M@N Posted October 15, 2010 Share Posted October 15, 2010 Hi guys I'm struggling a bit, I need to replace a word that occurs multiple times in text with an array("up","down","forward","backwards") of words. $find = "left"; $replace = array("up","down","forward","backwards"); $text = "left left left left"; echo str_replace($find,$replace,$text); The Output is: array array array array Did try this with a foreach statement as well, but no luck. Is there a better way of doing this? Thanks Quote Link to comment https://forums.phpfreaks.com/topic/215927-need-help-trying-to-replace-the-word-left-with-array123/ Share on other sites More sharing options...
chintansshah Posted October 15, 2010 Share Posted October 15, 2010 instead of echo str_replace($find,$replace,$text); try below $new_arr = str_replace($find,$replace,$text); print_r($new_arr); Quote Link to comment https://forums.phpfreaks.com/topic/215927-need-help-trying-to-replace-the-word-left-with-array123/#findComment-1122424 Share on other sites More sharing options...
Z33M@N Posted October 15, 2010 Author Share Posted October 15, 2010 instead of echo str_replace($find,$replace,$text); try below $new_arr = str_replace($find,$replace,$text); print_r($new_arr); Hi thanks, I tried it but still outputs: array array array array The result I'm looking for is: up down forward backwards How can I achieve that? Quote Link to comment https://forums.phpfreaks.com/topic/215927-need-help-trying-to-replace-the-word-left-with-array123/#findComment-1122442 Share on other sites More sharing options...
Pikachu2000 Posted October 15, 2010 Share Posted October 15, 2010 You need to loop through the array to do the replacement. Quote Link to comment https://forums.phpfreaks.com/topic/215927-need-help-trying-to-replace-the-word-left-with-array123/#findComment-1122479 Share on other sites More sharing options...
taquitosensei Posted October 15, 2010 Share Posted October 15, 2010 I'm not sure this will work, using str_replace to put an array in a string. unless you want the results to be "up down forwards backwards up down forwards backwards up down forwards backwards" etc.. then you would probably do str_replace($find,implode(" ",$array),$text); Quote Link to comment https://forums.phpfreaks.com/topic/215927-need-help-trying-to-replace-the-word-left-with-array123/#findComment-1122484 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.