dongyin0628 2018-09-27 07:55
浏览 65
已采纳

如何用连字符替换点,空格和逗号,并使用PHP避免双连字符?

When I replace spaces, dots and commas of a string, it sometimes happens that I get double hyphens.

For example turns check out the 1. place into check-out-the-1--place

How can I avoid that? I want it to be check-out-the-1-place - so that there only is one hyphen between each word. Here is my code:

str_replace([' ', ',', '.','?'], '-', strtolower($pathname));

Right now, I know why it returns the double-hyphens, but I don't know how to work around that.

Can someone help me out?

  • 写回答

2条回答 默认 最新

  • douduan5086 2018-09-27 08:18
    关注

    How can I avoid that? I want it to be check-out-the-1-place - so that there only is one hyphen between each word. Here is my code:

    Whilst Mohammad's answer is nearly there, here is a more fully working PCRE regex method and explanation as to how it works, so you can use it as you need:

    $str = trim(strtolower($pathname));
    $newStr = preg_replace('/[\s.,-]+/', '-', $str);
    

    How this works:

    • Match a single character present in the list below [\s.,-]+
      • + Quantifier Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
      • \s matches any whitespace character (equal to [ \t\f\v])
      • .,- matches a single character in the list .,- (case sensitive)
      • The dash - must come at the end of the [] set.

    Results:

    This: check out the 1. place

    Becomes:

    check-out-the-1-place

    And

    This: check out the - 1. place

    Becomes

    check-out-the-1-place


    Further:

    I would go further and assuming you are using this for a URL slug (a what?!); strip out all non-alphanumeric characters from the string and replace with a single - as per typical website slugs.

     $newStr = preg_replace('/[^a-z0-9]+/i', '-', $str);
    

    How this works:

    • Match a single character NOT (^) present in the list below [a-z0-9]+
      • + Quantifier Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
      • a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)
      • 0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
      • The i at the end indicates the judgements are case In-sensitive.

    Example:

    check out - the no.! 1. Place

    Becomes:

    check-out-the-1-Place

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

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行