str reemplazar con matriz


Estoy teniendo algunos problemas con la función PHP str_replace al usar arrays.

Tengo este mensaje:

$message = strtolower("L rzzo rwldd ty esp mtdsza'd szdepw ty esp opgtw'd dple");

Y estoy tratando de usar str_replace así:

$new_message = str_replace(
    array('l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a','b','c','d','e','f','g','h','i','j','k'),
    array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'),
    $message);

El resultado debería ser A good glass in the bishop's hostel in the devil's seat, pero en su lugar, obtengo p voos vlpss xn twt qxswop's wosttl xn twt stvxl's stpt.

Sin embargo, cuando solo intento reemplazar 2 letras, las reemplaza bien:

$new_message = str_replace(array('l','p'), array('a','e'), $message);

Las letras l y p será reemplazado por a y e.

¿Por qué no funciona con la matriz completa del alfabeto si ambos son ¿exactamente del mismo tamaño?

Author: Ry-, 2012-12-05

4 answers

str_replace con arrays solo realiza todos los reemplazos secuencialmente. Uso strtr en lugar de hacerlo todo a la vez:

$new_message = strtr($message, 'lmnopq...', 'abcdef...');
 31
Author: Ry-,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-16 10:44:41

Debido a que str_replace() reemplaza de izquierda a derecha, podría reemplazar un valor insertado previamente cuando se realizan múltiples reemplazos.

    // 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);
 40
Author: Rakesh Tembhurne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-05 03:38:26

Fácil y mejor que str_replace:

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

    $word = "http://desiweb.ir";
    echo strtr($word,$arr);
?>

strtr PHP doc aquí

 12
Author: desiweb.ir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-16 12:06:02

Alternativamente a la respuesta marcada como correcta, si tienes que reemplazar palabras en lugar de caracteres puedes hacerlo con este fragmento de código:

$query = "INSERT INTO my_table VALUES (?, ?, ?, ?);";
$values = Array("apple", "oranges", "mangos", "papayas");
foreach (array_fill(0, count($values), '?') as $key => $wildcard) {
    $query = substr_replace($query, '"'.$values[$key].'"', strpos($query, $wildcard), strlen($wildcard));
}
echo $query;

Demo aquí: http://sandbox.onlinephpfunctions.com/code/56de88aef7eece3d199d57a863974b84a7224fd7

 2
Author: TwystO,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-06 16:58:10