我正在創建一個作業公告網站。
目前,我一直在處理招聘公告內容中包含的URL。
我可以完美地將資料庫中的上述內容顯示到我的網站,但未檢測到URL。
在 Facebook 中,當您發布類似內容時,該網站會自動檢測這些鏈接。我也想在我自己的網站上實作這一點。

uj5u.com熱心網友回復:
在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>
<script> console.log('this is a hacking attempt hacking'); </script>
and <a href='www.google.com'>www.google.com</a>
also <a href='http://somesite.net'>http://somesite.net</a>
測驗https://3v4l.org/85lsl
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/443123.html
上一篇:如何在URL中提取主題標簽?
