title: PHP: Detect if string is a hyperlink and make it clickable
body: <p>In most chat applications when a user inputs a hyperlink, it automatically becomes clickable in the chat window. How do I replicate this behavior using PHP/JavaScript/JQuery?</p>
  
  <p>Essentially my idea of making it work is testing the chat message string for hyperlinks and encasing them in <code>&lt;a href&gt;</code> tags with themselves as the link. Is that correct, and if so, how do I do it? Also, how would I make it so that the links open in a new tab, instead of replacing my page?</p>
  
  <p><strong><em>EDIT</em></strong> This took me quite a bit of trial and error, but this PHP function <em>should</em> work in all realistic scenarios:</p>
  
  <pre><code>function formatTextLinks($text) {
      $words = preg_split("/[\s,]+/", $text);
      $offset = 0;
  
      foreach($words as $value) {
          preg_match("/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/", $value, $matches);
  
          $s = $matches[0];
          if(!is_string($s)) continue;
          $pos = strpos($text, $s, $offset);
          if($pos !== false) {
              $helper = "";
              if(strpos($s, "http://") === false || strpos($s, "https://") === false) $helper = "http://";
              $text = substr_replace($text, "&lt;a href='".$helper.$s."' target='_blank'&gt;".$s."&lt;/a&gt;", $pos, strlen($s));
              $offset = $pos + strlen("&lt;a href='".$helper.$s."' target='_blank'&gt;".$s."&lt;/a&gt;");
          }
      }
  
      return $text;
  }
  </code></pre>