joejacoem17
joejacoem17

Reputation: 35

Use str_replace for the string "/\/\" in PHP

How do I change these codes using PHP code ...

I tried this but failed.

$str = str_replace(
array('A','/\'),
array('M','/\/\'),
array('N','/\/'),
array('V','\/'),
array('W','\/\/'),
$html);

What is the best practice for doing this?

Upvotes: 0

Views: 30

Answers (2)

Nick
Nick

Reputation: 147146

You need to escape the backslashes. Also, you are not forming the parameters to str_replace correctly, they should be an array of strings and an array of replacements. This will do what you want:

$html = 'MAVEN WAR';
$str = str_replace(array('A', 'M', 'N', 'V', 'W'), 
                   array('/\\','/\\/\\','/\\/','\\/','\\/\\/'), 
                   $html);
echo $str;

Output:

/\/\/\\/E/\/ \/\//\R

Demo on 3v4l.org

Upvotes: 1

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

The correct way of using the str_replace is

$string = "ABCD This";
$pattern = ['A','B','C','D'];
$replacments = ['1A','2B','3C','4D'];
echo str_replace($pattern, $replacments, $string);

Upvotes: 0

Related Questions