Ho gli URL completi come stringhe, ma voglio rimuovere http: // all'inizio della stringa per visualizzare l'URL in modo appropriato (ad esempio: www.google.com di)PHP Regex per rimuovere http: // dalla stringa
Qualcuno può aiutare?
Ho gli URL completi come stringhe, ma voglio rimuovere http: // all'inizio della stringa per visualizzare l'URL in modo appropriato (ad esempio: www.google.com di)PHP Regex per rimuovere http: // dalla stringa
Qualcuno può aiutare?
$str = 'http://www.google.com';
$str = preg_replace('#^https?://#', '', $str);
echo $str; // www.google.com
che lavorerà sia per http://
e https://
Se ti ostini a usare RegEx:
preg_match("/^(https?:\/\/)?(.+)$/", $input, $matches);
$url = $matches[0][2];
Solo per completezza, aggiungerei un 's?' Dopo http. E sì, lo so che non era nella sua domanda. . . :)) –
Buona idea, aggiornata. – Overv
Perché non usare parse_url
invece?
Non hai bisogno di espressioni regolari. Utilizzare invece str_replace.
str_replace('http://', '', $subject);
str_replace('https://', '', $subject);
combinati in una sola operazione nel modo seguente:
str_replace(array('http://','https://'), '', $urlString);
Questo eliminerà anche eventuali corrispondenze successive di http (s): //, che potrebbe non essere un problema, ma potrebbe esserlo.Ad esempio se viene utilizzato in una stringa di query senza codifica url proprio – aland
Migliore utilizzo questo:
$url = parse_url($url);
$url = $url['host'];
echo $url;
semplice e funziona per http://
https://
ftp://
e quasi tutti i prefissi.
Questa è la risposta corretta! –
risposta corretta corretta !! +50 –
Sono contento che voi ragazzi sia piaciuto :) –
Per rimuovere http://domain (o https) e per ottenere il percorso:
$str = preg_replace('#^https?\:\/\/([\w*\.]*)#', '', $str);
echo $str;
Sì, penso che str_replace() e substr() sono più veloci e più pulito di espressioni regolari. Ecco una funzione rapida e sicura per questo. È facile vedere esattamente cosa fa. Nota: restituisci substr ($ url, 7) e substr ($ url, 8), se vuoi anche rimuovere //.
// 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;
}
Perché è necessario un regex? Perché non rimuovere solo i primi 7 caratteri? –
Controlla questo: http://stackoverflow.com/questions/4875085/php-remove-http-from-link-title – stefandoorn
@OliCharlesworth: Può essere anche 8 caratteri con 'https: //' – Sarfraz