title: Auto-link regular expression
body: <p>I am using a PHP function to automatically turn URLs in a text string into an actual link that people can click on. It seems to work in most cases, however I have found some cases where it does not.</p>
  
  <p>I don't really understand regular expressions at all, so I was hoping someone could help me out with this.</p>
  
  <p>Here is the pattern I'm currently using:</p>
  
  <pre><code>$pattern = "/(((http[s]?:\/\/)|(www\.))(([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+\.[a-z]+(\.[a-z]{2,2})?)\/?[a-z0-9.,_\/~#&amp;=;%+?-]+[a-z0-9\/#=?]{1,1})/is";
  </code></pre>
  
  <p>However here are some links I have found that this pattern is not matching:</p>
  
  <ul>
  <li>www.oakvilletransit.ca - Not sure, but assuming it doesn't match because of the two-letter country code</li>
  <li>www.grt.ca - Another one with the .ca domain that is not working</li>
  <li>Several other .ca addresses</li>
  <li>freepublictransports.com - Addresses without www. or http:// in front of them. I would like these to work as well.</li>
  <li>www.222tips.com - Assuming it doesn't match because of the numbers at the beginning of the address.</li>
  </ul>
  
  <p>Does anyone know how I can modify that regex pattern to match these cases as well?</p>
  
  <p><strong>EDIT</strong> - It should also match URLs that may have a period at the end. If a URL is the last part of a sentence there may be a period at the end that should not be included in the actual link. Currently this pattern takes that into account as well.</p>
  
  <p><strong>EDIT 2</strong> - I am using the pattern like this:</p>
  
  <pre><code>$pattern = "/((http|https):\/\/)?([a-z0-9-]+\.)?[a-z][a-z0-9-]+(\.[a-z]{2,6}){1,3}(\/[a-z0-9.,_\/~#&amp;=;%+?-]*)?/is";
    $string = preg_replace($pattern, " &lt;a target='_blank' href='$1'&gt;$1&lt;/a&gt;", $string);
    // fix URLs without protocols
    $string = preg_replace("/href='www/", "href='http://www", $string);
    return $string;
  </code></pre>