144

I remember doing this before, but can't find the code. I use str_replace to replace one character like this: str_replace(':', ' ', $string); but I want to replace all the following characters \/:*?"<>|, without doing a str_replace for each.

sameold
  • 18,400
  • 21
  • 63
  • 87
  • 2
    you want to replace all these chars with a space? – Book Of Zeus Sep 30 '11 at 02:53
  • 7
    Don't be afraid to reference the excellent php.net manual and [review the params section](http://php.net/str_replace) to see if what you want is possible. – Mike B Sep 30 '11 at 02:57

10 Answers10

239

Like this:

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

Or, in modern PHP (anything from 5.4 onwards), the slighty less wordy:

str_replace([':', '\\', '/', '*'], ' ', $string);
Codemonkey
  • 4,455
  • 5
  • 44
  • 76
Dogbert
  • 212,659
  • 41
  • 396
  • 397
133

str_replace() can take an array, so you could do:

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

Alternatively you could use preg_replace():

$new_str = preg_replace('~[\\\\/:*?"<>|]~', ' ', $string);
NullUserException
  • 83,810
  • 28
  • 209
  • 234
  • 2
    Assuming the OP meant that the backslash should be replaced, that preg_replace pattern didn't work for me. To get the backslash to work as expected, I had to use 4 of them (i.e. "\\\\") in the pattern. – GreenMatt Sep 30 '11 at 04:13
  • 1
    Good answer, adding @dogbert answer in would make it complete for the people who don't read the manual and don't realise str_split returns an array. – Bradmage Dec 31 '15 at 23:13
  • What's the advantage of `str_replace()` over `preg_replace()` (or vice-versa) in the OP's case? – aronmoshe_m Feb 12 '19 at 20:36
  • 1
    @ludditedev No real advantage either way, it's just a matter of preference – NullUserException Feb 23 '19 at 16:57
  • @NullUserException let's say I want to remove all these characters: `+-><` . Based on your answer, I tried: `preg_replace('~[\\+-><]~', '', $s);` . But it is removing the digits also (0-9). What is wrong ? Demo at: https://3v4l.org/inS5W – Madhur Bhaiya Sep 09 '19 at 10:08
  • 1
    @MadhurBhaiya Change the regex to `'~[\\+><-]~'` (note where the `-` is). The dash (`-`) is a regex metacharacter, so it needs to escaped or strategically placed in the character class (everything inside `[]`). See this answer: https://stackoverflow.com/a/7604888/396458 – NullUserException Sep 17 '19 at 17:21
99

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

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

// Output: replace1 replace2

Sumoanand
  • 8,835
  • 2
  • 47
  • 46
54
str_replace(
    array("search","items"),
    array("replace", "items"),
    $string
);
Marty
  • 39,033
  • 19
  • 93
  • 162
6

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

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
3

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

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

Output:

$s2: "the string          "

GreenMatt
  • 18,244
  • 7
  • 53
  • 79
1

I had a situation whereby 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

"Sprinkler and Fire Protection Installer", "Steamfitter ", "Terrazzo, Tile and Marble Setter",

Tempteh
  • 21
  • 2
0

I guess you are looking after this:

// example
private const TEMPLATE = __DIR__.'/Resources/{type}_{language}.json';

...

public function templateFor(string $type, string $language): string
{
   return \str_replace(['{type}', '{language}'], [$type, $language], self::TEMPLATE);
}
Erald Karakashi
  • 860
  • 8
  • 5
0

In my use case, I parameterized some fields in an HTML document, and once I load these fields I match and replace them using the str_replace method.

<?php echo str_replace(array("{{client_name}}", "{{client_testing}}"), array('client_company_name', 'test'), 'html_document'); ?>
dataviews
  • 2,466
  • 7
  • 31
  • 64
0

preg_replace() is the best for multiple items. Please check:

$invoice_no = preg_replace('~[\\+:><-]~', "",rand(0, 10) . now());

For single replacement you can use str_replace() :

$invoice_no = str_replace("-", "",rand(0, 1000) . now());