带数组的str_replace

Lau*_*ico 39 php arrays str-replace

str_replace使用数组时,我遇到了PHP函数的麻烦.

我有这样的信息:

$message = strtolower("L rzzo rwldd ty esp mtdsza'd szdepw ty esp opgtw'd dple");
Run Code Online (Sandbox Code Playgroud)

我试图这样使用str_replace:

$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);
Run Code Online (Sandbox Code Playgroud)

结果应该是A good glass in the bishop's hostel in the devil's seat,但相反,我得到了p voos vlpss xn twt qxswop's wosttl xn twt stvxl's stpt.

但是,当我只尝试更换2个字母时,它会很好地替换它们:

$new_message = str_replace(array('l','p'), array('a','e'), $message);
Run Code Online (Sandbox Code Playgroud)

字母lp将被替换ae.

如果它们的大小完全相同,为什么它不能使用完整的字母数组呢?

Rak*_*rne 50

因为str_replace()从左向右替换,所以在执行多次替换时,它可能会替换先前插入的值.

    // 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);

  • @TheSmose正如我所看到的问题是'为什么它不起作用......'而不是什么可以替代.所以我试着用一个例子来解释,为什么它不起作用. (10认同)

Ry-*_*Ry- 37

str_replace使用数组只是顺序执行所有替换.使用strtr,而不是做一次全部:

$new_message = strtr($message, 'lmnopq...', 'abcdef...');
Run Code Online (Sandbox Code Playgroud)

  • 请注意,您可以通过执行“$new_message = strtr('lmnopqrstuvwxyzabcdefghijkLMNOPQRSTUVWXYZABCDEFGHIJK','abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',$message);”来实现大小写工作 (2认同)

小智 16

简单而且比str_replace以下更好:

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

    $word = "http://desiweb.ir";
    echo strtr($word,$arr);
?>
Run Code Online (Sandbox Code Playgroud)

strtrPHP doc 在这里