Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP / RegEx - Convert URLs to links by detecting .com/.net/.org/.edu etc
    primarykey
    data
    text
    <p>I know there have been many questions asking for help converting URLs to clickable links in strings, but I haven't found quite what I'm looking for.</p> <p>I want to be able to match any of the following examples and turn them into clickable links:</p> <pre><code>http://www.domain.com https://www.domain.net http://subdomain.domain.org www.domain.com/folder subdomain.domain.net subdomain.domain.edu/folder/subfolder domain.net domain.com/folder </code></pre> <p>I do not want to match random.stuff.separated.with.periods.</p> <p>EDIT: Please keep in mind that these URLs need to be found within larger strings of 'normal' text. For example, I want to match 'domain.net' in "Hello! Come check out domain.net!".</p> <p>I think this could be accomplished with a regex that can determine whether the matching url contains .com, .net, .org, or .edu followed by either a forward slash or whitespace. Other than a user typo, I can't imagine any other case in which a valid URL would have one of those followed by anything else.</p> <p>I realize there are many valid domain extensions out there, but I don't need to support them all. I can just choose which to support with something like (com|net|org|edu) in the regex. Unfortunately, I'm not skilled enough with regex yet to know how to properly implement this.</p> <p>I'm hoping someone can help me find a regular expression (for use with PHP's preg_replace) that can match URLs based on just about any text connected by one or more dots and either ending with one of the specified extensions followed by whitespace OR containing one of the specified extensions followed by a slash and possibly folders.</p> <p>I did several searches and so far have not found what I'm looking for. If there already exists a SO post that answers this, I apologize. </p> <p>Thanks in advance.</p> <p>--- EDIT 3 ---</p> <p>After days of trial and error and some help from SO, here's what works:</p> <pre><code>preg_replace_callback('#(\s|^)((https?://)?(\w|-)+(\.(\w+|-)*)+(?&lt;=\.net|org|edu|com|cc|br|jp|dk|gs|de)(\:[0-9]+)?(?:/[^\s]*)?)(?=\s|\b)#is', create_function('$m', 'if (!preg_match("#^(https?://)#", $m[2])) return $m[1]."&lt;a href=\"http://".$m[2]."\"&gt;".$m[2]."&lt;/a&gt;"; else return $m[1]."&lt;a href=\"".$m[2]."\"&gt;".$m[2]."&lt;/a&gt;";'), $event_desc); </code></pre> <p>This is a modified version of anubhava's code below and so far seems to do exactly what I want. Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload