dtbi27903 2018-04-29 08:25
浏览 69
已采纳

PHP:将句子的单词组合成具有固定数量单词的较小组

I have sentence like this:

I am in love with you

I want this to be in following combination for 3 words from left to right.

I am in
am in love
in love with
love with you

I tried the code below, but I think I'm complicating it...

$data = array_chunk(explode(" ", $sarr), 3);
$data = array_map(function($value) {
    return sprintf("<span>%s</span>", implode(" ", $value));
}, $data);
echo implode("
", $data);

Any ideas on how to do it fast and efficiently? This must work for 5000 words.

  • 写回答

2条回答 默认 最新

  • duanqianruan8448 2018-04-29 08:47
    关注

    You could use Regular Expressions to work around this. You match one word then capture two other following words with a positive lookahead and stick them together within a foreach loop.

    $words = [];
    preg_match_all('~\b\w+(?=((?:\s+\w+){2}))~', $str, $matches);
    foreach ($matches[0] as $key => $word) {
        // 1st iteration => $word = "I", $matches[1][0] = " am in"
        $words[] = $word . $matches[1][$key];
    }
    

    Outputs (print_r($words);):

    Array
    (
        [0] => I am in
        [1] => am in love
        [2] => in love with
        [3] => love with you
    )
    

    Output of echo implode(PHP_EOL, $words);:

    I am in
    am in love
    in love with
    love with you
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私