如何使用爆炸在每三个空间之后拆分?

时间:2014-12-27 09:51:43

标签: php

我有一个字符串,如下所示:

$str = "In order to successfully build your backlinks in a highly competitive industry (or if you're targeting highly competitive keywords), you have to get smart about your strategy. That means using the best back-link building tools available";

现在我想在每第三个单词后分割字符串。那是我想要的..

split1 = in order to
split2 = successfully build your
split4 = backlinks in a

依此类推,直到字符串结尾。

我已经使用preg_match_all完成了它,但它没有给我我想要的东西。所以有人可以帮我解决使用split()或preg_split或explode()函数分割字符串的问题。

谢谢

1 个答案:

答案 0 :(得分:6)

$split = explode(' ', $str); // Split up the whole string
$chunks = array_chunk($split, 3); // Make groups of 3 words
$result = array_map(function($chunk) { return implode(' ', $chunk); }, $chunks); // Put each group back together

DEMO

$result是:

Array
(
    [0] => In order to
    [1] => successfully build your
    [2] => backlinks in a
    [3] => highly competitive industry
    [4] => (or if you're
    [5] => targeting highly competitive
    [6] => keywords), you have
    [7] => to get smart
    [8] => about your strategy.
    [9] => That means using
    [10] => the best back-link
    [11] => building tools available
)