Brian Moreno
Brian Moreno

Reputation: 1027

Regular Expression Validation PHP

I've been trying to get this to work for some time now but can't. Here is my problem:

I have the following reg. expression: (http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?. I'm trying to validate a URL.

The problem is when I have for example:

"https://www.youtube.com/watch?v=QK8mJJJvaes<br />Hello" (this is how it saves in the database using nl2br)

It validates up to this:https://www.youtube.com/watch?v=QK8mJJJvaes<br. I've read that the problem might be because of the \S* in the reg. expression. But if I take that out it only validates https://www.youtube.com/.

I've also thought of adding a space before the <br />, but I don't know if their is a better solution.

Any help is greatly appreciated :).

Full Code:

$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);
       }
 }

Upvotes: 0

Views: 338

Answers (1)

Dennis98
Dennis98

Reputation: 139

Change it to this:

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

This will at least validate your given URL, and any other that ends with a tag... Test it here: https://regex101.com/

EDIT: Isn't matching root paths. The solution from @Jonathan Kuhn in the comments is the best one:

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

UPDATE:

Just revisiting some old answers and I'm irritated why I commented like I did.. I don't see the problem though, your code works. :D

Although this short piece of code would do the same:

$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;

Upvotes: 1

Related Questions