match url pattern in php using regular expression

regular expression in php w3school
php regex
php regex cheat sheet
php match string
php preg_match case insensitive
java regex match url path
preg_match_all online
javascript regex

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

I would like the match 4 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 match url pattern '@(www?([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', then it only matches the third type of url pattern.

How can I match all four type of url pattern with a single regular expression?

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`!()\[\]{};:'".,<>?«»""‘’]))

PHP Regex: Cheat Sheet & Real-World Examples 2020, Regular expressions are powerful pattern matching algorithm that can be PHP has built in functions that allow us to work with regular functions. function to perform a simple pattern match for the word guru in a given URL. preg_match (string $pattern, string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]]) : int Searches subject for a match to the regular expression given in pattern.

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

PHP Regular Expressions Tutorial: Preg_match, Preg_split , URL matching is another regular expression headache, but I've included some of the more useful ones down below to help you get started matching your input. The forward slashes denote the beginning and end of our regular expression "'/pattern/'" is the pattern that we need to matched "subject" is the text string to be matched against; Let’s now look at practical examples that implement the above regular expression functions in PHP. PHP Preg_match. The first example uses the preg_match function to perform a simple pattern match for the word guru in a given URL.

I looked around and didn't see any that were exactly what I needed. I found this one that was close, so i modified it as follows:

^((([hH][tT][tT][pP][sS]?)\:\/\/)?([\w\\-]+(\[\w\.\&%\$\-]+)*)?((([^\s\(\)\<\>\\\"\.\   [\]\,;:]+)(\.[^\s\(\)\<\>\\\"\.\[\]\,;:]+)*(\.[a-zA-Z]{2,4}))|((([01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}([01]?\d{1,2}|2[0-4]\d|25[0-5])))(\b\:(6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}|0)\b)?((\/[^\/][\w\.\,\?\'\\\/\+&%\$#\=~_\-]*)*[^\.\,\?\"\'\(\)\[\]!;<>{}\s\x7F-\xFF])?)$

check it out on debuggex.

How to match URLs?, preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] ) : int Use the === operator for testing the return value of this function. Example #3 Getting the domain name out of a URL. We test all five words if they match with the pattern. $ php single.php Seven matches the pattern even does not match the pattern Maven does not match the pattern Amen does not match the pattern Leven matches the pattern The Seven and Leven words match our search pattern. PHP regex anchors. Anchors match positions of characters inside a given text.

I just checked this post (after 2 years) might be you got the answer but for those who are beginners, you can use regular expression to strip every type of URL or Query String

(https|http|ftp)\:\/\/|([a-z0-9A-Z]+\.[a-z0-9A-Z]+\.[a-zA-Z]{2,4})|([a-z0-9A-Z]+\.[a-zA-Z]{2,4})|\?([a-zA-Z0-9]+[\&\=\#a-z]+)

it will strip every type of URLs, take a look at the following list. I used different type of domains for those who want to ask "will it strip .us, .in or .pk etc type of domains or not.

  1. ftp://www.web.com
  2. web.net
  3. www.website.info
  4. website.us
  5. web.ws?query=true
  6. www.web.biz?query=true
  7. ftp://web.in?query=true
  8. media.google.com
  9. ns.google.pk
  10. ww1.smart.au
  11. www3.smart.br
  12. w1.smart.so
  13. ?ques==two&t=p
  14. http://website.info?ques==two&t=p
  15. https://www.weborwebsite.com

Working Example (tested in PHP5+, Apache2+):

$str = "ftp://www.web.com, web.net, www.website.info, website.us, web.ws?query=true, www.web.biz?query=true, ftp://web.in?query=true, media.google.com hello world, working more with ns ns.google.pk or ww1.smart.au and www3.smart.br w1.smart.so ?ques==two&t=p http://website.info?ques==two&t=p https://www.weborwebsite.com and ftp://www.hotmail.br";
echo preg_replace("/(https|http|ftp)\:\/\/|([a-z0-9A-Z]+\.[a-z0-9A-Z]+\.[a-zA-Z]{2,4})|([a-z0-9A-Z]+\.[a-zA-Z]{2,4})|\?([a-zA-Z0-9]+[\&\=\#a-z]+)/i", "", $str);

it will return

, , , , , , , hello world, working more with ns or and and

preg_match - Manual, The whole pattern is matched but none of the _ characters are placed in the it's better to describe your regular expression patterns using single-quoted strings. php,composer-php,autoload I have Composer in my PHP project installed, and want to use the autoloader. On this page I read how the composer.json file should look like and that I should run the command dump-autoload.

My two cents (five years later!):

preg_match("/^((https|http|ftp)\:\/\/)?([a-z0-9A-Z]+\.[a-z0-9A-Z]+\.[a-z0-9A-Z]+\.[a-zA-Z]{2,4}|[a-z0-9A-Z]+\.[a-z0-9A-Z]+\.[a-zA-Z]{2,4}|[a-z0-9A-Z]+\.[a-zA-Z]{2,4})$/i", $url)

PCRE regex syntax - Manual, Searches subject for all matches to the regular expression given in pattern and puts them in If you want your results grouped by individual match simply use: Pattern – The rule pattern is used to specify either the regular expression or a wildcard pattern that is used to match URL strings. Conditions – The optional conditions collection is used to specify additional logical operations to perform if a URL string matches the rule pattern. Within the conditions, you can check for certain values of HTTP headers or server variables, or verify if the requested URL corresponds to a file or directory on a physical file system.

preg_match_all - Manual, I have the following function to check if a string is a valid url: Obviously it's got something to do with the regex pattern, which is not my forte to put it mildly! If you have to match many slashes, then I would recommend not to� The preg_match () function searches a string for pattern, returning true if the pattern exists, and false otherwise. PHP - Validate E-mail The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var () function. In the code below, if the e-mail address is not well-formed, then store an error message:

Url validation with preg_match - PHP, A regular expression (or regex) is a group of characters used to find a pattern within a piece of text. In addition to matching many URLs, a regular expression can extract information from A frequently occurring problem with regular expression is an infinite redirect. Note that Redirection uses PHP's regular expressions. First of all, it is bad practice to use regular expressions for cascading content like (cascading) queries. But here we go Simply match the sequence of non-spaces after the FROM. Note: because of the greedyness of the Kleene star of the .*, it will definitely look for the latest match.

Redirect Regular Expressions, Regular Expression to Easy to identify your url. without prefix or with it. Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the foundation for pattern-matching functionality. Using regular expression you can search a particular string inside a another string, you can replace one string by another string and you can split a string into many chunks.

Comments
  • Note that there is a newer version of that regex here: daringfireball.net/2010/07/improved_regex_for_matching_urls
  • Implemented in PHP: http://stackoverflow.com/a/10002262/1055533
  • my goodness, finally this one works... i've been trying all kinds of ones that people have posted, either have trouble with the syntax or they partially work (what i needed to fix was that there were periods at the end of the url that were being picked up, like t.co/123213...)
  • Worked perfectly.