doushou6480 2010-04-13 06:47
浏览 253

使用PHP语言将所有空格和特殊符号替换为URL中的破折号

How to replace spaces and dashes when they appear together with only dash in PHP?

e.g below is my URL

http://kjd.case.150/1 BHK+Balcony- 700+ sqft. spacious apartmetn Bandra Wes

In this I want to replace all special characters with dash in PHP. In the URL there is already one dash after "balcony". If I replace the dash with a special character, then it becomes two dashes because there's already one dash in the URL and I want only 1 dash.

  • 写回答

5条回答

  • doucheng7808 2010-04-13 07:06
    关注

    If there could be max one space surrounding the hyphen you can use the answer by John. If there could be more than one space you can try using preg_replace:

    $str = preg_replace('/\s*-\s*/','-',$str);
    

    This would replace even a - not surrounded with any spaces with - !!

    To make it a bit more efficient you could do:

    $str = preg_replace('/\s+-\s*|\s*-\s+/','-',$str);
    

    Now this would ensure a - has at least one space surrounding it while its being replaced.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog