【问题标题】:str_replace with arraystr_replace 用数组
【发布时间】:2012-12-05 03:26:53
【问题描述】:

我在使用数组时遇到了 PHP 函数 str_replace 的一些问题。

我有这条消息:

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

我正在尝试像这样使用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);

结果应该是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);

字母 lp 将替换为 ae

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

【问题讨论】:

    标签: php arrays str-replace


    【解决方案1】:

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

    // 输出 F,因为 A 被 B 替换,然后 B 被 C 替换,依此类推... // 最后 E 被 F 替换,因为从左到右替换。 $search = array('A', 'B', 'C', 'D', 'E'); $replace = array('B', 'C', 'D', 'E', 'F'); $主题 = 'A'; echo str_replace($search, $replace, $subject);

    【讨论】:

    • 这没有提供比其他答案中已经提供的更多信息(这也解决了问题)。为你投反对票。
    • @TheSmose 正如我所见,问题是“为什么它不起作用......”而不是替代方案。所以我试着用一个例子来解释,为什么它不起作用。
    • 另一个答案说明了您在上面发布的确切“原因”,“如何解决它”。您以最小的方式回答 question 而不试图解决我的 problem 是违反 SO 的。另外,问题已经回答了,问题也解决了……
    • 谢谢,评论也有帮助。
    • 这是对发生这种情况的一个很好的清晰描述。谢谢。
    【解决方案2】:

    str_replace 使用数组只是按顺序执行所有替换。请改用strtr 一次性完成所有操作:

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

    【讨论】:

    • 注意,您可以通过 $new_message = strtr('lmnopqrstuvwxyzabcdefghijkLMNOPQRSTUVWXYZABCDEFGHIJK','abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',$message);
    【解决方案3】:

    str_replace简单更好:

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

    strtrPHP 文档 here

    【讨论】:

    • 对于那些想知道的人,stristr 应该用于需要不区分大小写的应用程序的场景。
    • @Tarquin 不完全 - stristr 是 strstr 的不区分大小写版本,而不是 strtr (这些名字!)对于像我一样想知道的人,可以在stackoverflow.com/questions/7529330/…
    【解决方案4】:

    除了标记为正确的答案之外,如果您必须替换单词而不是字符,您可以使用这段代码:

    $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;
    

    在这里演示:http://sandbox.onlinephpfunctions.com/code/56de88aef7eece3d199d57a863974b84a7224fd7

    【讨论】:

    • substr_replacestrpos 只是将 str_replace 设置为 1 的更长的编写方式。它与问题要求解决的问题相同。此外,此示例是 SQL 注入的秘诀。
    • 这里更好的方法是使用preg_replaceregexforeach($values as $value) { $query = preg_replace('/\\?/', $value, $query, 1); }
    【解决方案5】:

    如果文本是一个简单的标记并且有现有的锚点,请先暂存现有的锚点标签,换掉 url,然后替换暂存的标记。

    $text = '
    Lorem Ipsum is simply dummy text found by searching http://google.com/?q=lorem in your <a href=https://www.mozilla.org/en-US/firefox/>Firefox</a>,
    <a href="https://www.apple.com/safari/">Safari</a>, or https://www.google.com/chrome/ browser.
    
    Link replacements will first stage existing anchor tags, replace each with a marker, then swap out the remaining links.
    Links should be properly encoded.  If links are not separated from surrounding content like a trailing "." period then they it will be included in the link.
    Links that are not encoded properly may create a problem, so best to use this when you know the text you are processing is not mixed HTML.
    
    Example: http://google.com/i,m,complicate--d/index.html
    Example: https://www.google.com/chrome/?123&t=123
    Example: http://google.com/?q='. urlencode('<a href="http://google.com">http://google.com</a>') .'
    ';
    
    // Replace existing links with a marker
    $linkStore = array();
    $text = preg_replace_callback('/(<a.*?a>)/', function($match) use (&$linkStore){ $key = '__linkStore'.count($linkStore).'__'; $linkStore[$key] = $match[0]; return $key; }, $text);
    
    // Replace remaining URLs with an anchor tag
    $text = preg_replace_callback("/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/", function($match) use (&$linkStore){ return '<a href="'. $match[0] .'">'. $match[0] .'</a>'; }, $text);
    
    // Replace link markers with original
    $text = str_replace(array_keys($linkStore), array_values($linkStore), $text);
    
    echo '<pre>'.$text;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多