drqefnd544707688 2016-06-04 17:49
浏览 166
已采纳

PHP:根据逗号分隔的X计数将字符串拆分为2个字符串

So, I have a comma delimited string which I want to split into two strings after count of x commas.

So, if my string was as follows:

temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10

I want to split it into two strings after a count of 4 commas, I would expect:

$string1 = 'temp1, temp2, temp3, temp4, ';

$string2 = 'temp5, temp6, temp7, temp8, temp9, temp10';

How can I achieve this in PHP?

  • 写回答

8条回答 默认 最新

  • doulai5585 2016-06-04 17:59
    关注

    There are lots of ways to do this - one approach would be to explode the string and then implode slices of that array like this:

    $x = 4;
    $delim = ', ';
    $str = 'temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10';
    $parts = explode($delim,$str);
    $string1 = implode($delim,array_slice($parts,0,$x)) . $delim;
    $string2 = implode($delim,array_slice($parts,$x));
    

    To me, this is the cleanest and most readable way to get the job done and does not require a loop.

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!