完全なURLを文字列として使用していますが、文字列の先頭にhttp://を削除してURLをうまく表示したいとします(例:www.google.com http://www.google.com)URLからhttp://を削除するPHP Regex
誰かが助けることができますか?
完全なURLを文字列として使用していますが、文字列の先頭にhttp://を削除してURLをうまく表示したいとします(例:www.google.com http://www.google.com)URLからhttp://を削除するPHP Regex
誰かが助けることができますか?
あなたは正規表現を使用して主張する場合:
preg_match("/^(https?:\/\/)?(.+)$/", $input, $matches);
$url = $matches[0][2];
完全性のために、httpの後ろに 's? 'を追加します。そして、ええ、私はそれが彼の質問にはなかったことを知っています。 。 。 :)) –
良いアイデアが更新されました。 – Overv
のために働くのだろうか?
正規表現はまったく必要ありません。代わりにstr_replaceを使用してください。
str_replace(array('http://','https://'), '', $urlString);
これは、http(s)://の後続の一致も取り除きますが、これは問題ではないかもしれませんが、可能性もあります。たとえば、適切なURLコードなしのクエリ文字列で使用されている場合 – aland
より良い使用この:
$url = parse_url($url);
$url = $url['host'];
echo $url;
簡単かつhttp://
https://
ftp://
と、ほぼすべてのプレフィックスのために働くが、次のように単一の操作にまとめ
str_replace('http://', '', $subject);
str_replace('https://', '', $subject);
。
これは正解です! –
究極の正解!! +50 –
あなたが気に入ったのでうれしいです:) –
削除するhttp://domain(またはhttps)とパスを取得するには:
$str = preg_replace('#^https?\:\/\/([\w*\.]*)#', '', $str);
echo $str;
はええ、私はそのstr_replace()とSUBSTRを(と思う)より速く、正規表現よりもきれいです。ここには安全な高速機能があります。それが何をしているかを正確に見るのは簡単です。注意://を削除したい場合は、substr($ url、7)とsubstr($ url、8)を返します。
// slash-slash protocol remove https:// or http:// and leave // - if it's not a string starting with https:// or http:// return whatever was passed in
function universal_http_https_protocol($url) {
// Breakout - give back bad passed in value
if (empty($url) || !is_string($url)) {
return $url;
}
// starts with http://
if (strlen($url) >= 7 && "http://" === substr($url, 0, 7)) {
// slash-slash protocol - remove https: leaving //
return substr($url, 5);
}
// starts with https://
elseif (strlen($url) >= 8 && "https://" === substr($url, 0, 8)) {
// slash-slash protocol - remove https: leaving //
return substr($url, 6);
}
// no match, return unchanged string
return $url;
}
なぜ正規表現が必要ですか?なぜ最初の7文字を削除しないのですか? –
これをチェックしてください:http://stackoverflow.com/questions/4875085/php-remove-http-from-link-title – stefandoorn
@OliCharlesworth:これは 'https:// 'で8文字にすることもできます – Sarfraz