3

次の操作の実行に問題があります..

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

を削除しようとしており、URL の先頭に が追加されているhttps:// or http://ことを確認してwww.から、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 をフォーマットする方法についてご支援いただければ幸いです。また、http://またはhttps://を削除するためにstr_replaceで間違っていることについてもっと興味があります。私が間違っていることについて誰かが洞察を提供できれば、それは大歓迎です。

4

4 に答える 4

5

試してみてくださいparse_url()

戻り値

非常に不正な URL では、parse_url()FALSE を返すことがあります。

component パラメータを省略すると、連想配列が返されます。少なくとも 1 つの要素が配列内に存在します。この配列内の潜在的なキーは次のとおりです。

  • scheme- 例えばhttp
  • host
  • port
  • user
  • pass
  • path
  • query- 疑問符の後?
  • fragment- ハッシュマークの後#

したがって、次のコードでドメインにアクセスできます。

$url = "https://www.google.com/search...";
$details = parse_url($url);
echo($details['host']);
于 2012-10-18T16:52:24.110 に答える
4

行う

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

それ以外の

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

str_replace新しい文字列を返すため。変わりません$url

于 2012-10-18T16:55:48.053 に答える
1
$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.'/';
于 2012-10-18T18:01:35.177 に答える
1
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;
}

私の機能、希望が助けになる

于 2014-06-18T19:17:51.807 に答える