题
<强>重复:爆炸超过每隔一个的字 强>
$string = "This is my test case for an example."
如果我不爆炸基于' '
我得到一个
Array('This','is','my','test','case','for','an','example.');
我要的是一个爆炸每隔空间。
我正在寻找以下输出:
Array(
[0] => Array (
[0] => This is
[1] => is my
[2] => my test
[3] => test case
[4] => case for
[5] => for example.
)
所以基本上每2个措辞短语被输出。
任何人都知道的溶液????
解决方案
这将提供您正在寻找的输出
$string = "This is my test case for an example.";
$tmp = explode(' ', $string);
$result = array();
//assuming $string contains more than one word
for ($i = 0; $i < count($tmp) - 1; ++$i) {
$result[$i] = $tmp[$i].' '.$tmp[$i + 1];
}
print_r($result);
裹的函数:
function splitWords($text, $cnt = 2)
{
$words = explode(' ', $text);
$result = array();
$icnt = count($words) - ($cnt-1);
for ($i = 0; $i < $icnt; $i++)
{
$str = '';
for ($o = 0; $o < $cnt; $o++)
{
$str .= $words[$i + $o] . ' ';
}
array_push($result, trim($str));
}
return $result;
}
其他提示
一种替代,利用“追球”,将是这个片段。
$arr = explode( " ", "This is an example" );
$result = array();
$previous = $arr[0];
array_shift( $arr );
foreach( $arr as $current ) {
$result[]=$previous." ".$current;
$previous = $current;
}
echo implode( "\n", $result );
它总是有趣不需要索引和计数但保留所有这些内部表象的东西在foreach方法(或array_map,等等)。
没有循环短溶液(和可变字计数):
function splitStrByWords($sentence, $wordCount=2) {
$words = array_chunk(explode(' ', $sentence), $wordCount);
return array_map('implode', $words, array_fill(0, sizeof($words), ' '));
}
两个快速选项想到:通过每一个字爆炸和对重新组装,使用正则表达式来分割字符串,而不是爆炸()
。$arr = explode($string);
$arr2 = array();
for ( $i=0; $i<size($arr)-1; $i+=2 ) {
$arr2[] = $arr[i].' '.$arr[i+1];
}
if ( size($arr)%2==1 ) {
$arr2[] = $arr[size($arr)-1];
}
$ ARR2是解决方案。
$content="This is my test case for an example";
$tmp=explode(" ",$content);
$text = array();
$b=0;
for ($i = 0; $i < count($tmp)/2; $i++) {
$text[$i] = $tmp[$b].' '.$tmp[$b + 1];
$b++;
$b++;
}
print_r($text);
不隶属于 StackOverflow