Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match URL pattern in PHP using a regular expression

Tags:

regex

url

php

I want to match a URL link in a wall post and replace this link with anchor tag. For this I use the regular expression below.

I would like the match four types of URL:

  1. http://example.com
  2. https://example.com
  3. www.example.com
  4. example.com
preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@',
             '<a href="$1">$1</a>', $subject);

This expression matches only first two types of URL.

If I use this expression for matching a URL pattern, '@(www?([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', it only matches the third type of URL pattern.

How can I match all four typeS of URL patternS with a single regular expression?

like image 508
Seema Avatar asked Oct 11 '10 08:10

Seema


People also ask

What is a good RegEx to match a URL?

@:%_\+~#= , to match the domain/sub domain name.

Does PHP have pattern matching?

Checking information entered by users into a form is referred to as form validation. There are many different forms of validation, but the basic pattern match function in PHP is eregi , which stands for “evaluate regular expression, case insensitive”.

Which function is used for matching regular expression with a string in PHP?

Using preg_replace() The preg_replace() function will replace all of the matches of the pattern in a string with another string.


2 Answers

A complete working example using Nev Stokes' given link:

public function clickableUrls($html){
    return $result = preg_replace(
        '%\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))%s',
        '<a href="$1">$1</a>',
        $html
    );
}
like image 51
Mārtiņš Briedis Avatar answered Sep 18 '22 13:09

Mārtiņš Briedis


I'd use a different regex to be honest. Like this one that Gruber posted in 2009:

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

Or this updated version that Gruber posted in 2010 (thanks, @IMSoP):

(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
like image 45
Nev Stokes Avatar answered Sep 20 '22 13:09

Nev Stokes