Jump to content

Multiple str_replace


cjackson111

Recommended Posts

Hello. I am pulling data from a mysql table and want to replace some strings that may appear in the data. Is it possible to use str_replace to replace more than one value at a time? For instance, replace '+' with 'plus'  AND '-' with 'minus'.

 

This doesn't work but something like this --

 

str_replace($search1, $replace1, $subject1,  $search2, $replace2, $subject2);

 

Thanks for all help!

Link to comment
Share on other sites

You can use an array:

$search = array ('item1' , 'item2')
$replace = array('replace1' , 'replace2')
str_replace($search, $replace, $subject)

 

If you have a second subject, just redo the str_replace line with $subject2 instead

 

another solution (if you have not that many replace to do) you cando something like:

 

str_replace($search, $replace, str_replace($search, $replace, $subject))

 

innesting any times you want

Link to comment
Share on other sites

another solution (if you have not that many replace to do) you cando something like:

 

str_replace($search, $replace, str_replace($search, $replace, $subject))

 

innesting any times you want

 

This would just result in a very messy code even if it does work. but I don't see why you have str_replace() inside str_replace()

Link to comment
Share on other sites

If your replacement strings are similar you can use strstr. Although slower, it will prevent overwriting of previous replacements as it only replaces each replacement string ones and "locks" it for writing (token).

 

strstr doesn't directly replace. Disregard the above post.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.