如何用正则匹配每隔一个空格?实现PHP字符串双词分组
问题描述
我有这段PHP字符串:
$title1 = "Lorem Ipsum simply dummy text of the printing and typesetting industry Lorem has been the industry ";
想要把它拆成两两单词一组的数组,最终结果要像这样:
( [0] => "Lorem Ipsum" [1] => "simply dummy" [2] => "text of" [3] => "the printing" [4] => "and typesetting" [5] => "industry Lorem" [6] => "has been" [7] => "the industry" )
试了preg_split("/ /", $title1),但只能拆出单个单词的数组,达不到预期效果。
办法1:用正则直接匹配两两单词组合
直接用preg_match_all匹配连续的两个单词,还能自动处理字符串里的多余空格:
$title1 = "Lorem Ipsum simply dummy text of the printing and typesetting industry Lorem has been the industry "; // 先去掉首尾的多余空格 $cleanStr = trim($title1); // 匹配所有"单词+空格+单词"的组合 preg_match_all('/(\S+ \S+)/', $cleanStr, $matches); $result = $matches[1]; // 输出来看结果 print_r($result);
运行后就能得到你要的数组。
办法2:先拆单个单词再手动分组
如果不想用正则,也可以先把字符串拆成单个单词的数组,再循环把每两个单词拼在一起:
$title1 = "Lorem Ipsum simply dummy text of the printing and typesetting industry Lorem has been the industry "; // 拆分单词,同时处理多个空格的情况 $words = preg_split('/\s+/', trim($title1)); $result = []; // 每次跳2个索引,取两个单词合并 for ($i = 0; $i < count($words); $i += 2) { // 防止最后只剩一个单词的情况(你的示例里是偶数个,所以这个判断可选) $result[] = isset($words[$i+1]) ? $words[$i] . ' ' . $words[$i+1] : $words[$i]; } print_r($result);
这种方法逻辑更直观,方便后续调整分组规则。
内容的提问来源于stack exchange,提问作者Osman Kara
相关产品推荐
相关产品推荐

