PHP 字符串分割

发布于 2024-08-27 18:19:53 字数 294 浏览 7 评论 0原文

我需要将字符串拆分为 2,2,3,3 个字符的块,并且能够通过使用 unpack 在 Perl 中执行此操作:

unpack("A2A2A3A3", 'thisisloremipsum');

但是相同的函数在 PHP 中不起作用,它给出以下输出:

Array
(
    [A2A3A3] => th
)

我怎样才能做到这一点使用解包?我不想为它编写一个函数,它应该可以通过 unpack 但如何实现呢?

提前致谢,

I need to split a string into chunks of 2,2,3,3 characters and was able to do so in Perl by using unpack:

unpack("A2A2A3A3", 'thisisloremipsum');

However the same function does not work in PHP, it gives this output:

Array
(
    [A2A3A3] => th
)

How can I do this by using unpack? I don't want to write a function for it, it should be possible with unpack but how?

Thanks in advance,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你爱我像她 2024-09-03 18:19:53

引用 unpack 的手册页:

unpack() 工作方式略有不同
来自 Perl 的解压数据是
存储在关联数组中。

要实现这一目标,您必须
命名不同的格式代码用斜杠/分隔它们。

Which means that, using something like this :

$a = unpack("A2first/A2second/A3third/A3fourth", 'thisisloremipsum');
var_dump($a);

您将得到以下输出:

array
  'first' => string 'th' (length=2)
  'second' => string 'is' (length=2)
  'third' => string 'isl' (length=3)
  'fourth' => string 'ore' (length=3)

Quoting the manual page of unpack :

unpack() works slightly different
from Perl as the unpacked data is
stored in an associative array.

To accomplish this you have to
name the different format codes and separate them by a slash /.

Which means that, using something like this :

$a = unpack("A2first/A2second/A3third/A3fourth", 'thisisloremipsum');
var_dump($a);

You'll get the following output :

array
  'first' => string 'th' (length=2)
  'second' => string 'is' (length=2)
  'third' => string 'isl' (length=3)
  'fourth' => string 'ore' (length=3)
半世晨晓 2024-09-03 18:19:53

我从未使用过此函数,但根据文档,A 字符表示“空格填充的字符串”。所以我大胆猜测它只采用第一个单词的前两个字符。

您是否尝试过 unpack("A2A2A3A3", 'this is lorem ipsum');

I've never used this function, but according to the documentation, the A character means "SPACE-padded string". So I'd hazard a guess that it's only taking the first two characters of the first word.

Have you tried unpack("A2A2A3A3", 'this is lorem ipsum'); ?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文