正则表达式验证PHP

问题描述 投票:0回答:1

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

我有以下注册。表达:(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);
       }
 }
php regex
1个回答
1
投票

把它改成这个:

/(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;
© www.soinside.com 2019 - 2024. All rights reserved.