PHP去除URLhttps://等

Published
2022-11-23
浏览次数 :  8

URL Decode

<?php
    // Decode the Encoded URL
    $input = "http%3A%2F%2Fway2tutorial.com%2F";
    $input = urldecode($input);

    // Output http://way2tutorial.com/
    echo $input;
?>

Remove http:// from the URL

<?php
    // Remove http://
    $input = "http://way2tutorial.com";
    $input = preg_replace( "#^[^:/.]*[:/]+#i", "", $input );

    /* Output way2tutorial.com */
    echo $input;
?>

Add http:// in the URL

<?php
    // Add http://
    $input = 'www.way2tutorial.com';

    // Check, if not have http:// or https:// then prepend it
    if (!preg_match('#^http(s)?://#', $input)) {
        $input = 'http://' . $input;
    }

    // Output http://www.way2tutorial.com
    echo $input;
?>

Remove http://, www., and slashes from the URL

<?php
    $url = 'http://www.way2tutorial.com/tutorial/';

    print_r(parse_url($url));

    echo parse_url($url, PHP_URL_PATH);
//give your array 
Array
(
    [scheme] => http
    [host] => www.way2tutorial.com
    [path] => /tutorial/
)

/tutorial/

    // Remove the http://, www., and slash(/) from the URL 
    $input = 'www.way2tutorial.com/';

    // If URI is like, eg. www.way2tutorial.com/
    $input = trim($input, '/');

    // If not have http:// or https:// then prepend it
    if (!preg_match('#^http(s)?://#', $input)) {
        $input = 'http://' . $input;
    }

    $urlParts = parse_url($input);

    // Remove www.
    $domain_name = preg_replace('/^www\./', '', $urlParts['host']);

    // Output way2tutorial.com
    echo $domain_name;
?>


?>

shorthand

<?php
    // Short way to do All this one
    // Encoded URL to Decode the URL, Remove the http://, www., and slash(/) from the URL 
    $input = "http%3A%2F%2Fway2tutorial.com%2F";  

    // Output way2tutorial.com      
    echo preg_replace( "#^[^:/.]*[:/]+#i", "", preg_replace( "{/$}", "", urldecode( $input ) ) );  
?>

Top