str_replace with array str_replace with array php php

str_replace with array


Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.

    // Outputs F because A is replaced with B, then B is replaced with C, and so on...    // Finally E is replaced with F, because of left to right replacements.    $search  = array('A', 'B', 'C', 'D', 'E');    $replace = array('B', 'C', 'D', 'E', 'F');    $subject = 'A';    echo str_replace($search, $replace, $subject);


str_replace with arrays just performs all the replacements sequentially. Use strtr instead to do them all at once:

$new_message = strtr($message, 'lmnopq...', 'abcdef...');


Easy and better than str_replace:

<?php$arr = array(    "http://" => "http://www.",    "w" => "W",    "d" => "D");    $word = "http://desiweb.ir";    echo strtr($word,$arr);?>

strtr PHP doc here