title: PHP - Replace URL in text with Links OR Images
body: <p>Doesn't matter how much I try, I can't figure this out.
  I have a comments section on my website and I have some functions using regex expressions.
  One of mine functions replaces URLs in the content string in links, as long as it can, it is working pretty well. But I wanted to check if the match is a normal link or if it is an image (ends with .jpg, .gif, etc) if so, it should then have the replace expression with <code>&lt;img&gt;</code> tags.
  What I have so for:</p>
  
  <pre><code>function url_parse($string) {
      $string = preg_replace('/\b(?:(http(s?):\/\/)|(?=www\.))(\S+)/is', '&lt;a href="http$2://$3" target="_blank"&gt;$1$3&lt;/a&gt;', $string);
      return $string; 
  }
  </code></pre>
  
  <p>This one is the function to replace the links. Easy as that. But my idea to check if it is a image, I made alot of confusions here. I don't even know how to extact the link, so I do this:</p>
  
  <pre><code>function geturl($string) {
      $regex = '/\b(?:(http(s?):\/\/)|(?=www\.))(\S+)/is';
      preg_match_all($regex, $string, $matches);
      return ($matches[0]);
  }
  </code></pre>
  
  <p>I even made a function to check if it is actually a link to a image</p>
  
  <pre><code>function isIMG($url){
      $ext = strrpos( $url, ".");
      if ($pos === false) {
          return false;
      }
      $ext = strtolower(trim(substr( $url, $pos)));
      $exts = array(".gif", ".jpg", ".jpeg", ".png", ".tiff", ".tif");
      if (in_array($ext, $exts)) {
          return true;
      }
      else {
         return false;
      }
  }
  </code></pre>
  
  <p>But, I got myself into a LIMBO. I just can't put it all working together. I tried everything... Any help? </p>
  
  <p>The objective here is: </p>
  
  <ol>
  <li><p>Check if the URL extracted from the string is a normal link OR if it have an image ext.</p></li>
  <li><p><code>preg_replace</code> in the string.
  I hope that this question doesn't seem messed up. Really needing any help here.</p></li>
  </ol>