正则表达式验证 PHP


Regular Expression Validation PHP

我一直在尝试让它工作一段时间了,但不能。这是我的问题:

我有以下注册表达式:(http|https|ftp|ftps)':'/'/[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}('/'S*)? .我正在尝试验证网址。

问题是当我有例如:

" https://www.youtube.com/watch?v=QK8mJJJvaes<br />Hello "(这是它使用 nl2br 保存在数据库中的方式)

它验证到此:https://www.youtube.com/watch?v=QK8mJJJvaes<br .我读到问题可能是因为 reg. 表达式中的'S*。但是如果我把它拿出来,它只会验证https://www.youtube.com/.

我也想过在<br />之前添加一个空格,但我不知道是否有更好的解决方案。

:),非常感谢任何帮助。

完整代码:

$reg_exUrl = "/(http|https|ftp|ftps)':'/'/[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}('/'S*)?/";
// The Text you want to filter for urls
$finalMsg = 'https://www.youtube.com/watch?v=QK8mJJJvaes<br />Hello';
// Check if there is a url in the text
if(preg_match_all($reg_exUrl, $finalMsg, $url)){
       // make the urls hyper links
       $matches = array_unique($url[0]);
       foreach($matches as $match) {
              $replacement = "<a href=".$match." target='_blank'>{$match}</a>";
              $finalMsg = str_replace($match,$replacement,$finalMsg);
       }
 }

将其更改为:

/(http|https|ftp|ftps)':'/'/[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}('/'S[^<]*)?/

这至少会验证您给定的 URL,以及任何其他以标签结尾的 URL......在这里测试:https://regex101.com/

编辑:与根路径不匹配。@Jonathan Kuhn 在评论中的解决方案是最好的:

/(http|https|ftp|ftps)':'/'/[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}('/[^'s<]*)?/

更新:

只是重温一些旧的答案,我很生气为什么我像我一样发表评论。不过我没有看到问题,您的代码有效。:D

尽管这短段代码可以做同样的事情:

$url = "https://www.youtube.com/watch?v=QK8mJJJvaes<br />Hello";
$regex = '/(http|https|ftp|ftps)':'/'/[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}('/[^'s<]*)?/';
// make the URLs hyperlinks
$url = preg_replace($regex, '<a href="$0" target="_blank">$0</a>', $url);
echo $url;