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

How to replace dots, spaces and commas with hyphen and avoid double hyphen using php?

当我替换字符串的空格、点和逗号时,有时会出现双连字符。

例如把check out the 1. place变成check-out-the-1--place

我怎样才能避免这种情况?我希望它是 check-out-the-1-place - 这样每个单词之间只有一个连字符。 这是我的代码:

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

现在,我知道为什么它 returns 双连字符,但我不知道如何解决这个问题。

有人能帮帮我吗?

您可以改用 preg_replace() 并使用正则表达式来选择多个特定字符。

$newStr = preg_replace("/[\s.,]+/", "-", $str)

检查结果 demo

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:

同时 is nearly there, here is a more fully working PCRE regex 方法及其工作原理的解释,因此您可以根据需要使用它:

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

这是如何工作的:

  • 匹配下面列表中的单个字符 [\s.,-]+
    • +量词匹配一次和无限次次,尽可能多次,按需回馈(贪心)
    • \s 匹配任何空白字符(等于 [\r\n\t\f\v])
    • .,- 匹配列表中的单个字符 .,-(区分大小写)
    • 破折号 - 必须出现在 [] 集合的 末尾 处。

结果:

This: check out the 1. place

变成:

check-out-the-1-place

This: check out the - 1. place

变成

check-out-the-1-place


进一步:

我会走得更远,假设您将其用于 URL 鼻涕虫 (a what?!);从字符串中删除 所有 非字母数字字符,并根据典型的网站 slug 替换为单个 -

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

这是如何工作的:

  • 匹配单个字符 NOT (^) 出现在下面的列表中 [a-z0-9]+
    • +量词匹配一次和无限次次,尽可能多次,按需回馈(贪心)
    • a-z a(索引 97)和 z(索引 122)之间的单个字符(区分大小写)
    • 0-9 0(索引 48)和 9(索引 57)之间的单个字符(区分大小写)
    • 最后的i表示判断是case In-sensitive.

示例:

check out - the no.! 1. Place

变成:

check-out-the-1-Place