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
https://forums.phpfreaks.com/topic/250911-multiple-str_replace/
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

  Quote

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

  Quote

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()

  Quote

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.

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.