Jazuly
Jazuly

Reputation: 321

how to Str_replace for multiple items

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?

Upvotes: 1

Views: 3095

Answers (1)

ishegg
ishegg

Reputation: 9937

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.

Upvotes: 3

Related Questions