1

I use str_replace to replace one character like this:
str_replace("--","/",$value['judul']).

but I want to replace 2 character like this:
str_replace("--","/",$value['judul']) and
str_replace("-+-",":",$value['judul'])
without doing two str_replace. can i just using one str-replace?

Jazuly
  • 321
  • 1
  • 4
  • 15
  • Possible duplicate of [How to replace multiple items from a text string in PHP?](https://stackoverflow.com/questions/9393885/how-to-replace-multiple-items-from-a-text-string-in-php) – localheinz Sep 02 '17 at 10:26

1 Answers1

3

You can use strtr() and an associative array to do this:

<?php
$text = "Text about -- and -+- !";
$replacements = [
    "--" => "/",
    "-+-" => ":",
];
echo strtr($text, $replacements); // Text about / and : !

To add more replacements, simply keep adding more elements to the $replacements array. Index is the string to look for, value is the replacement.

ishegg
  • 9,685
  • 3
  • 16
  • 31
  • 1
    @Jazuly `str_replace` also could be used with an array, might want to look at https://stackoverflow.com/questions/8177296/when-to-use-strtr-vs-str-replace for the differences. – chris85 Sep 02 '17 at 01:25
  • @chris85 `str_replace()` is a bit more annoying for this because you need two arrays. He wanted to reduce the verbosity I guess so that’s why I suggested this. Thanks for the suggestion! – ishegg Sep 02 '17 at 01:26
  • 1
    @ishegg You _could_ use array_keys and array_values with one array. (I find nothing wrong with your answer, just a note that there might be different behavior) – chris85 Sep 02 '17 at 01:30
  • Never thought of that, it's a great idea! Thank you. – ishegg Sep 02 '17 at 01:32