youthweb / urllinker
自动链接文本或HTML中的URL
2.0.0
2022-12-14 13:25 UTC
Requires
- php: ^7.4 || ^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.13
- phpstan/phpstan: ^1.9
- phpunit/phpunit: ^9
README
UrlLinker可以将纯文本中的任何网页地址转换为HTML超链接。
这是一个对Kwi\UrlLinker(原位于Bitbucket)伟大工作的维护分支。
安装
通过Composer
$ composer require youthweb/urllinker
用法
$urlLinker = new Youthweb\UrlLinker\UrlLinker(); $linkedText = $urlLinker->linkUrlsAndEscapeHtml($text); $linkedText = $urlLinker->linkUrlsInTrustedHtml($html);
您可以通过传递给UrlLinker::__construct()
来为解析URL配置不同的选项。
$config = [ // Ftp addresses like "ftp://example.com" will be allowed, default false 'allowFtpAddresses' => true, // Uppercase URL schemes like "HTTP://exmaple.com" will be allowed: 'allowUpperCaseUrlSchemes' => true, // Add a Closure to modify the way the urls will be linked: 'htmlLinkCreator' => function(string $url, string $content): string { return '<a href="' . $url . '" target="_blank">' . $content . '</a>'; }, // ..or add a callable as a Closure to modify the way the urls will be linked: 'htmlLinkCreator' => [$class, 'linkCreator'](...), // Add a Closure to modify the way the emails will be linked: 'emailLinkCreator' => function(string $email, string $content): string { return '<a href="mailto:' . $email . '" class="email">' . $content . '</a>'; }, // ... or add a callable as a Closure to modify the way the emails will be linked: 'emailLinkCreator' => \Closure::fromCallable('callableFunction'), // ... or you can also disable the links for email with a closure: 'emailLinkCreator' => fn (string $email, string $content): string => $email, // You can customize the recognizable Top Level Domains: 'validTlds' => ['.localhost' => true], ]; $urlLinker = new Youthweb\UrlLinker\UrlLinker($config);
支持的地址
- 网页地址
- 支持的URL方案: "http" 和 "https"
- “http://”前缀是可选的。
- 可以通过将
allowFtpAddresses
设置为true
轻松添加对其他方案的支持,例如 "ftp"。 - 方案必须小写。可以通过将
allowUpperCaseUrlSchemes
设置为true
来取消此要求。
- 可以使用域名或IPv4地址指定主机。
- 不支持IPv6地址。
- 允许端口号。
- 允许国际化资源标识符(IRIs)。注意,将IRIs转换为URI的任务留给了用户的浏览器。
- 为了减少误报,UrlLinker会验证顶级域名是否在官方IANA有效TLD列表中。
- 随着TLD列表的扩展,UrlLinker会定期更新。
- 将来,这种方法可能会因为ICANN不恰当的新政策——以大量现金出售任意TLD——而失效,但目前它是一种有效拒绝无效URL的方法。
- 为了识别,国际化的顶级域名必须以Punycode编写。
- 如果您只想支持某些特定的TLD,可以通过将它们设置为
validTlds
,例如['.com' => true, '.net' => true]
。 - 如果您需要支持非限定域名,例如
localhost
,您也可以在validTlds
中将它们设置为['.localhost' => true]
。
- 支持的URL方案: "http" 和 "https"
- 电子邮件地址
- 支持常见的地址格式,包括“加号地址”(如Gmail所推广的)。
- 不识别RFC允许但实践中从未见过的更神秘的地址变体。
- 简单的垃圾邮件防护:将at符号转换为HTML实体,以防止无知的电子邮件地址收集器。
- 如果您不想链接电子邮件,可以在
emailLinkCreator
中设置一个简单的闭包,该闭包仅返回原始电子邮件,如下所示:function($email, $content) { return $email; }
。
- 在正常句子环境中可以正确识别地址。例如,在“Visit stackoverflow.com.”中,最后的句点不是URL的一部分。
- 用户输入经过适当的清理,以防止跨站脚本(XSS),并且URL中的&符号被正确转义为
&
(这不适用于linkUrlsInTrustedHtml()
函数,该函数假定其输入是有效的HTML)。
变更日志
有关最近更改的更多信息,请参阅CHANGELOG。
测试
单元测试使用PHPUnit编写。
$ phpunit
贡献
请随时提交错误或派生分支并发送Pull Requests。本项目遵循语义化版本控制2.0和PSR-2。
许可证
GPL3。有关更多信息,请参阅许可证文件。