Exploding a string into equal portions

穿精又带淫゛_ 提交于 2019-12-24 09:59:36

问题


$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);

so this gives me $pieces[0] = 'Hello',$pieces[1] = 'fri3nd'... and the rest of the string is all shoved into$pieces[3]`. How can I explode into every 3 or 4 words?


回答1:


Maybe:?

<?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);

Explanation:

  • first you split the string at any (combined) whitespace: preg_split
  • then 'split' the resulting array: array_chunk
  • you then apply implode using array_map on any resulting group of words



回答2:


Use the php str_split function:-

$pieces = str_split( $str, 3);


来源:https://stackoverflow.com/questions/6173250/exploding-a-string-into-equal-portions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!