【问题标题】:PHP: Convert English normal text to URL [duplicate]PHP:将英文普通文本转换为 URL [重复]
【发布时间】:2016-09-15 13:22:30
【问题描述】:

我尝试将普通英文文本转换为 url 路径。

例如

  • this is a text! -> this-is-a-text
  • this is a text&image -> this-is-a-text-image
  • are you ok? -> are-you-ok

所以我尝试使用以下代码进行转换:

str_replace("-", "+", urlencode(trim($text)));

它不会将+ 转换为-

另外,对于 '/' 和 '&' 似乎也不起作用(对于某些字符串不起作用。)

有没有更好的办法?

【问题讨论】:

标签: php url urlencode


【解决方案1】:

对于您的示例,这应该有效:

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

如果您想要全部小写,请改用strtolower($text),则不需要i 修饰符。

【讨论】:

  • 快速打字机,正是我的想法,这里有 101 个 regex101.com/r/vU1lP6/1
  • $result = trim(preg_replace('/[^a-z0-9]+/i', '-', strtolower($text)), '-'); - 添加了+strtolower;修剪
  • @luchaninov:谢谢!
【解决方案2】:

这个过程通常被称为“制造蛞蝓”。 您可以为此找到各种准备好的功能。 考虑到 Unicode,函数可能会更复杂。

但是,您的问题在这里得到了解答: PHP function to make slug (URL string)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 2012-02-14
    • 2018-08-26
    • 1970-01-01
    • 2012-10-14
    • 2021-08-23
    • 2016-06-24
    相关资源
    最近更新 更多