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条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀