我在一个简单的PHP字符串中有一个句子:
$myString = "This is a test.";
我想要一个包含两个单词或两组单词之间所有可能连接的数组,如下所示(空格作为分隔符):
$myArray = [
["This", "is"],
["This", "is a"],
["This", "is a test."],
["This is", "a"],
["This is", "a test."],
["This is a", "test."],
["is", "a"],
["is", "a test."],
["is a", "test."],
["a", "test."]
];
它必须尽可能快地运行,希望在输入字符串的单次扫描中。
编辑:
这是我到目前为止所使用的递归函数:
/**
* @param string $string
* @return string[]
*/
private function split($string)
{
$whitespace = strpos($string, ' ');
if (false === $whitespace) {
return;
}
$segment = substr($string, 0, $whitespace);
$string = substr($string, $whitespace + 1);
$this->link($segment, $string);
$this->split($string);
}
/**
* @param string $segment
* @param string $string
*/
private function link($segment, $string)
{
$this->links[] = [$segment, $string];
}
然后我致电$this->split('this is a test');
并获得:
var_dump($this->links);
Array
(
[0] => Array
(
[0] => This
[1] => is a test.
)
[1] => Array
(
[0] => is
[1] => a test.
)
[2] => Array
(
[0] => a
[1] => test.
)
)
每次调用link()方法时我都要向后移动$ links数组,但是大文档的计算成本太高了。