duanji9677 2012-02-18 22:11
浏览 67
已采纳

使用str_replace时的数组到字符串转换通知

When I use str_replace with an array as second argument like in the much upvoted and accepted answer to this question, I get an array to string conversion notice. Why? Example:

$str = 'a b a ba a';
$numerals = range(1, 10);
$str = str_replace('a', $numerals, $str);

gives :

PHP Notice: Array to string conversion in php shell code on line 1

and the following output:

Array b Array bArray Array

instead of

1 b 2 b3 4

  • 写回答

1条回答 默认 最新

  • dongxiao9583 2012-02-18 22:27
    关注

    You are trying to replace one character ('a') with multiple characters (1,2,3,4,5,6,7,8,9,10). PHP can't figure that out and tries to convert this array to string. When you're using string as $search parameter you must also use string as $replace parameter. An array as $replace parameter can be used only when $search is also an array. Quoting from documentation:

    If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though.

    Here's the code that will work:

    $str = 'a b a ba a';
    $count = 1;
    while(($letter_pos = strpos($str, 'a')) !== false) {
        $str = substr_replace($str, $count++, $letter_pos, 1);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题