I am having some trouble performing the following operation..
http://www.google.com –> http://www.google.com/
https://google.com –> http://www.google.com/
google.com –> http://www.google.com/
I am trying to remove https:// or http://, ensure that www. is added to the beginning of the URL, and then add a trailing slash to the URL if it does not exist.
Feeling like I’ve gotten the majority of this figured out but I can’t get str_replace() to work how I’d like it to.
To my understanding this is how to use str_replace:
$string = 'Hello friends';
str_replace('friends', 'enemies', $string);
echo $string;
// outputs 'Hello enemies' on the page
Here is what I have so far:
$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
}
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.
Do
instead of
because
str_replacereturns a new string; it doesn’t change$url.