Ich habe vollständige URLs als Zeichenfolgen, aber ich möchte das http: // am Anfang der Zeichenfolge entfernen, um die URL schön anzuzeigen (z. B. www.google.com anstelle von http://www.google.com )
Kann jemand helfen?
$str = 'http://www.google.com';
$str = preg_replace('#^https?://#', '', $str);
echo $str; // www.google.com
Das funktioniert sowohl für http://
als auch für https://
Sie brauchen überhaupt keinen regulären Ausdruck. Verwenden Sie stattdessen str_replace .
str_replace('http://', '', $subject);
str_replace('https://', '', $subject);
In einem einzigen Vorgang wie folgt kombiniert:
str_replace(array('http://','https://'), '', $urlString);
Nutzen Sie das besser:
$url = parse_url($url);
$url = $url['Host'];
echo $url;
Einfacher und funktioniert für http://
https://
ftp://
und für fast alle Präfixe.
Warum nicht stattdessen parse_url
verwenden?
So entfernen Sie http: // domain (oder https) und erhalten den Pfad:
$str = preg_replace('#^https?\:\/\/([\w*\.]*)#', '', $str);
echo $str;
Wenn Sie auf der Verwendung von RegEx bestehen:
preg_match( "/^(https?:\/\/)?(.+)$/", $input, $matches );
$url = $matches[0][2];
Ja, ich denke, dass str_replace () und substr () schneller und sauberer sind als reguläre Ausdrücke. Hier ist eine sichere schnelle Funktion dafür. Es ist leicht zu sehen, was genau es tut. Hinweis: Geben Sie substr ($ url, 7) und substr ($ url, 8) zurück, wenn Sie auch // entfernen möchten.
// 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;
}
<?php
// (PHP 4, PHP 5, PHP 7)
// preg_replace — Perform a regular expression search and replace
$array = [
'https://lemon-kiwi.co',
'http://lemon-kiwi.co',
'lemon-kiwi.co',
'www.lemon-kiwi.co',
];
foreach( $array as $value ){
$url = preg_replace("(^https?://)", "", $value );
}
Diese Code-Ausgabe:
lemon-kiwi.co
lemon-kiwi.co
lemon-kiwi.co
www.lemon-kiwi.co
Siehe Dokumentation PHP preg_replace