Joh*_*one 3 php regex arrays string
我试图在PHP中将字符串拆分为单词对数组.例如,如果您有输入字符串:
"split this string into word pairs please"
Run Code Online (Sandbox Code Playgroud)
输出数组应该是这样的
Array (
[0] => split this
[1] => this string
[2] => string into
[3] => into word
[4] => word pairs
[5] => pairs please
[6] => please
)
Run Code Online (Sandbox Code Playgroud)
一些失败的尝试包括:
$array = preg_split('/\w+\s+\w+/', $string);
Run Code Online (Sandbox Code Playgroud)
这给了我一个空数组,和
preg_match('/\w+\s+\w+/', $string, $array);
Run Code Online (Sandbox Code Playgroud)
它将字符串拆分为单词对但不重复单词.是否有捷径可寻?谢谢.
为什么不使用爆炸?
$str = "split this string into word pairs please";
$arr = explode(' ',$str);
$result = array();
for($i=0;$i<count($arr)-1;$i++) {
$result[] = $arr[$i].' '.$arr[$i+1];
}
$result[] = $arr[$i];
Run Code Online (Sandbox Code Playgroud)