title: Format URL using PHP - http://www.google.com to www.google.com/; Also having trouble with str_replace()
body: <p>I am having some trouble performing the following operation..</p>
  
  <blockquote>
    <p><a href="http://www.google.com" rel="nofollow">http://www.google.com</a> --> www.google.com/<br />
    <a href="https://google.com" rel="nofollow">https://google.com</a> --> www.google.com/<br />
    google.com --> www.google.com/</p>
  </blockquote>
  
  <p>I am trying to remove <code>https:// or http://</code>, ensure that <code>www.</code> is added to the beginning of the URL, and then add a trailing slash to the URL if it does not exist.</p>
  
  <p>Feeling like I've gotten the majority of this figured out but I can't get <code>str_replace()</code> to work how I'd like it to.</p>
  
  <p>To my understanding this is how to use <code>str_replace</code>:</p>
  
  <pre><code>$string = 'Hello friends';
  str_replace('friends', 'enemies', $string);
  echo $string;
  // outputs 'Hello enemies' on the page
  </code></pre>
  
  <p>Here is what I have so far:</p>
  
  <pre><code>$url = 'http://www.google.com';
  
  echo reformat_url($url);
  
  function reformat_url($url) {
      if ( substr( $url, 0, 7 ) == 'http://' || substr( $url, 0, 8 ) == 'https://' ) { // if http:// or https:// is at the beginning of the url
          $remove = array('http://', 'https://');
          foreach ( $remove as $r ) {
              if ( strpos( $url, $r ) == 0 ) {
                  str_replace($r, '', $url); // remove the http:// or https:// -- can't get this to work
              }
          }
      }
      if ( substr( $url, 0, 4 ) != 'www.') { // if www. is not at the beginning of the url
          $url = 'www.' . $url; // prepend www. to the beginning
      }
      if ( substr( $url, -1 ) !== '/' ) { // if trailing slash does not exist
          $url = $url . '/';  // add trailing slash
      }
      return $url; // return the formatted url
  }
  </code></pre>
  
  <p>Any assistance on a way to format the URL would be greatly appreciated; also I'm more curious regarding what I am doing wrong with str_replace to remove http:// or https://. If anyone could offer some insight as to what I am doing incorrectly it'd be greatly appreciated.</p>