dtjkl42086 2010-11-17 10:12
浏览 52
已采纳

删除字符串中变量的重复?

Say you have a string like:

  $string = 'hello my name is blah blah and wats yours';

And you wanted to go through and check for any places where there might be a duplication.. not of any word, but just of the chosen word in this instance 'blah'.

   $variable = 'blah';

Ie, if 'blah' appears back to back - remove one of them.

I consider splitting the string into an array and if one variable in the array starts with the same word the last one ended with then cut out one and rebuild the string. Seems tedius so this is why I am asking if there might be a simpler way.

Any ideas?

edit: i just realised i didn't consider doing a preg_match of simply 'blah blah' with 'blah'.

  • 写回答

4条回答 默认 最新

  • doubi12138 2010-11-17 10:31
    关注

    How about this:

    $string = 'hello my name is blah blah and wats yours';
    $variable = 'blah';
    $string = preg_replace( '/(\b'.$variable.'\s+){2,}/' , '\1' , $string );
    

    Allows for more than one variable to be handled (ie you could either loop through a number of $variables or you could create an array of them and use a single preg_replace() call.

    Or just use a str_replace()

    $string = 'hello my name is blah blah and wats yours';
    $variable = 'blah';
    $string = str_replace( $variable.' '.$variable.' ' , $variable.' ' , $string );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器