duanboniao5903 2018-08-08 13:33
浏览 277
已采纳

PHP中的字符串数组(检查2个或更多字符串是否具有相同的开头)

My question seems a little bit silly, but I don't know why I can't seem to make the code work.

I have an array of strings and want to do the following:

When I find 2, 3 or n elements starting with the same 3 letters exp 09_ I want to make it one element seperated by ***. i tried to do this

for ($j=0;$j<count($list1)-1;$j++)
    { 
        $begin= substr($list1[$j], 0, 3).'<br>';
        //echo $list1[$j].'<br>';


        if( strpos( $list1[$j], $begin ) !== false) 
        {
            $list1[$j]=$list1[$j].'***'.$list1[$j+1];
          unset($list1[$j+1]);
          $list1 = array_values($list1);
        }

        echo $list1[$j].'<br>';
    }

I have this array:

('01_order','09_customer bla bla bla ','09_customer bla1 bla1 bla1','09_customer bla2 bla2 bla2')

I want to make it look like this array

('01-order','09_customer bla bla bla * 09_customer bla1 bla1 bla1* 09_customer bla2 bla2 bla2')

Please give me some ideas

Thank you

  • 写回答

3条回答 默认 最新

  • duanbangzhou7809 2018-08-08 13:43
    关注

    Make a temporary array indexed by substrings and implode the new array's items

    $res = [];
    
    foreach($list1 as $x) { 
       $res[substr($x, 0, 3)][] = $x;
    }
    
    
    foreach($res as &$x) {
       $x = implode('***', (array) $x);
    }
    
    print_r($res);
    

    demo on eval

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置