将php字符串拆分为不同长度的块 [英] split php string into chunks of varying length

查看:178
本文介绍了将php字符串拆分为不同长度的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找将字符串拆分为数组的方法,例如str_split(),其中的块大小均不同.

I am looking for ways to split a string into an array, sort of str_split(), where the chunks are all of different sizes.

我可以通过用一串substr()遍历字符串来做到这一点,但是看起来既不优雅也不高效.是否有一个函数可以接受一个字符串和一个数组,例如(1, 18, 32, 41, 108, 125, 137, 152, 161),并产生一个经过适当切碎的字符串片段的数组?

I could do that by looping through the string with a bunch of substr(), but that looks neither elegant nor efficient. Is there a function that accept a string and an array, like (1, 18, 32, 41, 108, 125, 137, 152, 161), and yields an array of appropriately chopped string pieces?

爆炸是不合适的,因为大块由不同数量的空格分隔.

Explode is inappropriate because the chunks are delimited by varying numbers of white spaces.

推荐答案

PHP中没有什么可以为您做到的(有点具体).因此,就像radashk只是siad一样,您只需要编写一个函数

There is nothing in PHP that will do that for you (it's a bit specific). So as radashk just siad, you just have to write a function

function getParts($string, $positions){
    $parts = array();

    foreach ($positions as $position){
        $parts[] = substr($string, 0, $position);
        $string = substr($string, $position);
    }

    return $parts;
}

类似的东西.然后,您可以在任何喜欢的地方使用它,这样就很干净:

Something like that. You can then use it wherever you like, so it's clean:

$parts = getParts('some string', array(1, ... 161));

如果您确实愿意,可以将其内嵌为正则表达式:

If you really wanted to, you could implode it into a regular expression:

^.{1}.{18} <lots more> .{161}$

将满足您的需求.

这篇关于将php字符串拆分为不同长度的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆