代码之家  ›  专栏  ›  技术社区  ›  Ibrahim Azhar Armar

如何用一个字符替换一个或多个连续空格?

php
  •  5
  • Ibrahim Azhar Armar  · 技术社区  · 14 年前

    我想生成字符串一样搜索引擎优化友好的网址。我要消除多个空格,用连字符替换单个空格( - ),然后 strtolower 不允许使用特殊字符。

    为此,我现在是这样的代码:

    $string = htmlspecialchars("This    Is The String");
    $string = strtolower(str_replace(htmlspecialchars((' ', '-', $string)));
    

    以上代码将生成多个连字符。我想去掉多个空间,用一个空间代替它。简言之,我正在努力实现搜索引擎优化友好的网址一样的字符串。我该怎么做?

    3 回复  |  直到 14 年前
        1
  •  18
  •   Paul Dixon    14 年前

    你可以用 preg_replace 用破折号替换任意空格字符序列。。。

     $string = preg_replace('/\s+/', '-', $string);
    
    • 外斜杠是模式的分隔符-它们只是标记模式的开始和结束位置
    • \s匹配任何 whitespace character
    • +使上一个元素 match 1 or more times . 默认情况下,这是“贪婪的”,因此它会吃掉尽可能多的连续匹配。
    • 请参阅上的手册页 PCRE syntax 更多细节
        2
  •  0
  •   powtac    14 年前
    echo preg_replace('~(\s+)~', '-', $yourString);
    
        3
  •  0
  •   Yeroon    14 年前

    你想要的是“敲击”一根弦。在SO或google上搜索“php slugify”或“php slug”。