如何用连字符替换点、空格和逗号并避免使用 php 使用双连字符? [英] How to replace dots, spaces and commas with hyphen and avoid double hyphen using php?
问题描述
当我替换字符串的空格、点和逗号时,有时会出现双连字符.
When I replace spaces, dots and commas of a string, it sometimes happens that I get double hyphens.
例如将check out the 1. place
变成 check-out-the-1--place
我怎样才能避免这种情况?我希望它是 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.
有人可以帮我吗?
推荐答案
我怎样才能避免这种情况?我希望它是 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:
虽然穆罕默德的答案几乎在那里,但这里有一个更完整的PCRE regex 方法及其工作原理的说明,因此您可以将其用作你需要:
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);
这是如何工作的:
- 匹配出现在下面列表中的单个字符
[\s.,-]+
+
量词在一次和无限次之间匹配,尽可能多次,根据需要回馈(贪婪)\s
匹配任何空白字符(等于 [\r\n\t\f\v
]).,-
匹配列表中的单个字符.,-
(区分大小写)- 破折号
-
必须位于[]
集的末尾.
- 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 [\r\n\t\f\v
]).,-
matches a single character in the list.,-
(case sensitive)- The dash
-
must come at the end of the[]
set.
结果:
这个:看看 1. 地方
This: check out the 1. place
变成:
check-out-the-1-place
还有
这个:看看 - 1. 地方
This: check out the - 1. place
成为
check-out-the-1-place
我会更进一步,假设您将它用于 URL slug (什么?!);从字符串中去除所有 非字母数字字符,并按照典型的网站 slug 替换为单个
-
.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);
这是如何工作的:
- 匹配出现在
[a-z0-9]+
下方列表中的单个字符NOT (^
)+
量词在一次和无限次之间匹配,尽可能多次,根据需要回馈(贪婪)a-z
a(索引 97)和 z(索引 122)之间范围内的单个字符(区分大小写)0-9
0(索引 48)和 9(索引 57)之间范围内的单个字符(区分大小写)- 末尾的
i
表示判断不区分大小写.
- 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.
示例:
退房 - 没有!1. 放置
check out - the no.! 1. Place
变成:
check-out-the-1-Place
这篇关于如何用连字符替换点、空格和逗号并避免使用 php 使用双连字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!