将字符串转换为不带连续连字符的 slug
我正在尝试创建一个执行几个不同替换规则的变量。例如,如果变量名称返回时带有空格,我会将其替换为连字符。如果它包含 & 符号,则会将其从字符串中删除。现在我有这个:
$reg_ex_space = "[[:space:]]";
$replace_space_with = "-";
$reg_ex_amper = "[&]";
$replace_amper_with = "";
$manLink1 = ereg_replace ($reg_ex_amper, $replace_amper_with, $manName);
$manLink2 = ereg_replace ($reg_ex_space, $replace_space_with, $manLink1);
当我从带有 & 符号的东西中回显 manLink2 时,请说 Tom & Jerry
,它将返回Tom--Jerry
。
有人可以解释一下更有效/更有效的写法吗?
I am trying to create a variable that performs a couple of different replacement rules. For example, if the variable name comes back with a space I replace it with a hyphen. If it contains an ampersand then it removes it from the string. Right now I have this:
$reg_ex_space = "[[:space:]]";
$replace_space_with = "-";
$reg_ex_amper = "[&]";
$replace_amper_with = "";
$manLink1 = ereg_replace ($reg_ex_amper, $replace_amper_with, $manName);
$manLink2 = ereg_replace ($reg_ex_space, $replace_space_with, $manLink1);
and when I echo manLink2 from something that has an ampersand, say Tom & Jerry
, it will return Tom--Jerry
.
Can someone please explain a more efficient/working way to write this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这会将
&
替换为空白字符串(将其删除),并将空格转换为-
。然后它会将多个
-
压缩为一个。CodePad。
This will replace
&
with blank string (removing it) and convert spaces to-
.It will then condense multiple
-
together to one.CodePad.
要对字符串进行 slugify,只需匹配一个或多个非白名单字符,然后用单个连字符替换匹配的子字符串即可。
代码:(演示)
To slugify your string, simply match one or more of any non-whitelisted characters then replace that matched substring with a single hyphen.
Code: (Demo)