簡體   English   中英

使用PHP格式化URL - http://www.google.com到www.google.com/; 也有str_replace()的問題

[英]Format URL using PHP - http://www.google.com to www.google.com/; Also having trouble with 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

這是我到目前為止:

$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
}

任何有關格式化URL的方法的幫助都將不勝感激; 我對str_replace刪除http://或https://的錯誤更感興趣。 如果有人能夠提供一些關於我正在做錯誤的見解,那將非常感激。

試試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']);

$url = str_replace($r, '', $url);

代替

str_replace($r, '', $url);

因為str_replace返回一個新字符串; 它不會改變$url

$url = str_replace('http://', '', $url);
$url = str_replace('https://', '', $url);
if(substr( $url, 0, 4 ) != 'www.')
{
    $url = 'www.'.$url;
}
$length = strlen($url);
if($url[$length-1] != '/')
$url = $url.'/';
public static function formatURLs($t) {
    $t = ' '.$t;
    $t = preg_replace("#([\s]+)([a-z]+?)://([a-z0-9\-\.,\?!%\*_\#:;~\\&$@\/=\+]+)#i", "\\1<a href=\"\\2://\\3\" rel=\"nofollow\" target=\"_blank\">\\3</a>", $t);
    $t = preg_replace("#([\s]+)www\.([a-z0-9\-]+)\.([a-z0-9\-.\~]+)((?:/[a-z0-9\-\.,\?!%\*_\#:;~\\&$@\/=\+]*)?)#i", "\\1<a href=\"http://www.\\2.\\3\\4\" rel=\"nofollow\" target=\"_blank\">\\2.\\3\\4</a>", $t);
    $t = preg_replace("#([\s]+)([a-z0-9\-_.]+)@([\w\-]+\.([\w\-\.]+\.)?[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $t);
    $t = substr($t, 1);
    return $t;
}

我的功能,希望會有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM