【问题标题】:How to convert URLs containing Unicode characters into clickable links?如何将包含 Unicode 字符的 URL 转换为可点击的链接?
【发布时间】:2010-08-05 10:01:53
【问题描述】:

我使用这个函数来创建指向可点击链接的 URL,但问题是当 URL 中有一些 Unicode 字符时,它只会在该字符之前变成可点击链接...

功能:

function clickable($text) {
    $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
                          '<a class="und" href="\\1">\\1</a>', $text);
    $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
                          '\\1<a href="http://\\2">\\2</a>', $text);
    $text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',
                          '<a href="mailto:\\1">\\1</a>', $text);

return $text;

}

如何解决这个问题?

【问题讨论】:

  • 尝试用字符类:digit::alpha::lower::upper: 等替换硬编码的a-zA-Z
  • (旁注) 自 PHP 5.3.0 起,POSIX Regex functions 已被弃用。考虑改用PCRE family

标签: php regex url


【解决方案1】:

首先,不要使用eregi_replace。我不认为它可以与 unicode 一起使用 - 它从 php 5.3 开始贬值。使用preg_replace

那你可以试试类似的东西

preg_replace("/(https?|ftps?|mailto):\/\/([-\w\p{L}\.]+)+(:\d+)?(\/([\w\p{L}\/_\.#]*(\?\S+)?)?)?/u", '<a href="$0">$0</a>

编辑 - 更新表达式以包含 # 字符

【讨论】:

  • 一个问题,当url中有#符号时它会中断!如何解决这个问题?
【解决方案2】:

尝试使用 \p{L} 代替 a-zA-Z 和 \p{Ll} 代替 a-z

您可以在正则表达式here中找到有关unicode处理的详细信息

并养成使用 preg 函数而不是已弃用的 ereg 函数的习惯

【讨论】:

    猜你喜欢
    • 2021-05-13
    • 2022-11-24
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 2021-08-26
    • 1970-01-01
    相关资源
    最近更新 更多