自动检测文本中的 URL 个链接

Automatically detect URL links in a text

我正在创建一个职位发布网站。

目前,我一直在处理招聘公告内容中包含的URL

我可以完美地将我数据库中的上述内容显示到我的网站,但是 URL 未检测到

在 Facebook 中,当您 post 类似的内容时,网站会自动检测这些链接。 我也想在我自己的网站上实现这个

A Liberal, Accurate Regex Pattern for Matching URLs 中我发现了以下 Regex

\b(([\w-]+://?|www[.])[^\s()<>]+(?:([\w\d]+)|([^[:punct:]\s]|/)))

解决方案

/**
 * @param string $str the string to encode and parse for URLs
 */
function preventXssAndParseAnchors(string $str): string
{
    $url_regex = "/\b((https?:\/\/?|www\.)[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/)))/";

    // Encoding HTML special characters To prevent XSS
    // Before parsing the URLs to Anchors
    $str = htmlspecialchars($str, ENT_QUOTES, 'UTF-8');

    preg_match_all($url_regex, $str, $urls);

    foreach ($urls[0] as $url) {
        $str = str_replace($url, "<a href='$url'>$url</a>", $str);
    }

    return $str;
}

例子

<?php
$str = "
apply here https://ph.dbsd.com/job/dfvdfg/5444

<script> console.log('this is a hacking attempt hacking'); </script>

and www.google.com

also http://somesite.net
";

echo preventXssAndParseAnchors($str);

输出

apply here <a href='https://ph.dbsd.com/job/dfvdfg/5444'>https://ph.dbsd.com/job/dfvdfg/5444</a>

&lt;script&gt; console.log(&#039;this is a hacking attempt hacking&#039;); &lt;/script&gt;

and <a href='www.google.com'>www.google.com</a>

also <a href='http://somesite.net'>http://somesite.net</a>

测试https://3v4l.org/85lsl