【问题标题】:Exploding a string into equal portions将字符串分解成相等的部分
【发布时间】:2011-05-30 07:04:49
【问题描述】:
$str =  "Hello fri3nd, you're looking good today!  What a Great day this is!  How     fancy and cool!";
$pieces = explode(" ",$str, 3);

print_r($pieces);

所以这给了我$pieces[0] = 'Hello',$pieces[1] = 'fri3nd'... and the rest of the string is all shoved into$pieces[3]`。我怎样才能爆炸成每 3 或 4 个单词?

【问题讨论】:

  • 在你的标题中,你问的是相等的部分,在问题中,你问的是每 3 或 4 个单词。它是哪一个,您希望它如何准确地工作?
  • 你能解释一下你的要求和情况吗?为什么要用 3 或 4 个单词来分割?如果您能解释您的要求,我们可能会提出最佳解决方案。

标签: php arrays explode


【解决方案1】:

也许:?

<?php
$str =  "Hello fri3nd, you're looking good today!  What a Great day this is!  How     fancy and cool!";

$array = array_map(create_function('$a', 'return implode(" ", $a);'), array_chunk(preg_split('/\s+/', $str), 3));
var_dump($array);

解释:

  • 首先在任何(组合)空白处拆分字符串:preg_split
  • 然后“拆分”结果数组:array_chunk
  • 然后,您可以使用 array_mapimplode 应用于任何生成的单词组

【讨论】:

  • 哇..这似乎有效..但我能解释一下发生了什么吗?它有这么多的功能结合在一起!
  • 似乎我还是太笨了,无法理解这里发生的一切......但我真的很感激它
  • 为什么在可以使用explode(' ', 的地方使用正则表达式? Explode 更快。
  • @Matthieu 因为您可能会得到空数组条目(请参阅字符串末尾附近的许多空格)
  • 对于投反对票的人,你能解释一下你的动机吗?
【解决方案2】:

使用phpstr_split函数:-

$pieces = str_split( $str, 3);

【讨论】:

  • 不分词。它只是把整个东西粉碎成碎片。按单词爆炸,但我无法选择将它们“爆炸”分开的方式。
猜你喜欢
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 2014-10-21
  • 2013-09-25
相关资源
最近更新 更多