Str_replace for multiple items

I remember how it was done before, but I can not find the code. I use str_replace to replace a single character as follows: str_replace(':', ' ', $string); but I want to replace all the following characters \/:*?"<>| without doing str_replace for each.

+53
string php str-replace
Sep 30 2018-11-11T00:
source share
7 answers

str_replace() can take an array so you can:

 $new_str = str_replace(str_split('\\/:*?"<>|'), ' ', $string); 

Alternatively, you can use preg_replace() :

 $new_str = preg_replace('~[\\\\/:*?"<>|]~', ' ', $string); 
+63
Sep 30 2018-11-11T00:
source share

Like this:

 str_replace(array(':', '\\', '/', '*'), ' ', $string); 

Or, in modern PHP (something since 5.4 years old), slightly less verbose:

 str_replace([':', '\\', '/', '*'], ' ', $string); 
+113
Sep 30 '11 at 2:53
source share
 str_replace( array("search","items"), array("replace", "items"), $string ); 
+34
Sep 30 2018-11-11T00:
source share

For example, if you want to replace search1 with replace1 and search2 with replace2, then the following code will work:

 print str_replace( array("search1","search2"), array("replace1", "replace2"), "search1 search2" ); 

// Exit: replace1 replace2

+33
Feb 10 '15 at 20:36
source share

If you are replacing only single characters, you should use strtr()

+6
Sep 30 2018-11-11T00:
source share

You can use preg_replace () . The following example can be run using the php command line:

 <?php $s1 = "the string \\/:*?\"<>|"; $s2 = preg_replace("^[\\\\/:\*\?\"<>\|]^", " ", $s1) ; echo "\n\$s2: \"" . $s2 . "\"\n"; ?> 

Output:

$ s2: "string

+1
Sep 30 2018-11-11T00:
source share

I had a situation where I had to replace the HTML tags with two different replacement results.

 $trades = "<li>Sprinkler and Fire Protection Installer</li> <li>Steamfitter </li> <li>Terrazzo, Tile and Marble Setter</li>"; $s1 = str_replace('<li>', '"', $trades); $s2 = str_replace('</li>', '",', $s1); echo $s2; 

result

"Installer of sprinklers and fire protection", "Steamboat", "Terrazzo, Tile and Marble Setter",

0
Feb 15 '17 at 18:19
source share



All Articles