PHP在其他单词上突然爆炸了吗? [英] PHP explode over every other word with a twist?

查看:53
本文介绍了PHP在其他单词上突然爆炸了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重复项:彼此展开字

Duplicate: Explode over every other word

$string = "This is my test case for an example."

如果我确实基于' '爆炸,我会得到

If I do explode based on ' ' I get an

Array('This','is','my','test','case','for','an','example.');

我想要的是爆炸其他所有空间.

What I want is an explode for every other space.

我正在寻找以下输出:

Array( 

[0] => Array ( 

[0] => This is
[1] => is my
[2] => my test
[3] => test case 
[4] => case for 
[5] => for example. 

)

所以基本上每2个词组都会输出一次.

so basically every 2 worded phrases is outputted.

有人知道解决方案吗??

Anyone know a solution????

推荐答案

这将提供您要查找的输出

this will provide the output you're looking for

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

这篇关于PHP在其他单词上突然爆炸了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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