使用PHP格式化URL - http://www.google.com到www.google.com/; 还有str_replace()的问题

kyl*_*rns 3 php url substr str-replace

我在执行以下操作时遇到了一些麻烦..

http://www.google.com - > www.google.com/
https://google.com - > www.google.com/
google.com - > www.google.com/

我试图删除https:// or http://,确保将www.其添加到URL的开头,然后如果URL不存在则向URL添加尾部斜杠.

感觉就像我已经把这个中的大部分弄清楚但是我无法开始str_replace()工作我是怎么想的.

根据我的理解,这是如何使用str_replace:

$string = 'Hello friends';
str_replace('friends', 'enemies', $string);
echo $string;
// outputs 'Hello enemies' on the page
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止:

$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
}
Run Code Online (Sandbox Code Playgroud)

任何有关格式化URL的方法的帮助都将不胜感激; 我对str_replace删除http://或https://的错误更感兴趣.如果有人能够提供一些关于我正在做错误的见解,那将非常感激.

rek*_*ire 5

试试parse_url().

返回值

对于严重格式错误的URL,parse_url()可能会返回FALSE.

如果省略component参数,则返回关联数组.阵列中至少存在一个元素.此数组中的潜在键是:

  • scheme - 例如 http
  • host
  • port
  • user
  • pass
  • path
  • query - 问号后 ?
  • fragment - 在hashmark之后 #

因此,您可以使用以下代码访问域:

$url = "https://www.google.com/search...";
$details = parse_url($url);
echo($details['host']);
Run Code Online (Sandbox Code Playgroud)