CodeIgniter Forums
regex to eliminate port number from url - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: regex to eliminate port number from url (/showthread.php?tid=68241)



regex to eliminate port number from url - cupboy1 - 06-14-2017

I tried this and some other things. What I need in this example would be to return just localhost without the colon and the port number. There may or may not be a port number and it needs to return a value in both cases. Currently it returns 'localhost:8080' in [1][0] but I want just 'localhost' to be in there.


Code:
$subject1 = "localhost:8080";
$subject2 = "localhost";

$pattern = "/(.*)\:{0,1}(.*)/";

$retval = preg_match($pattern, $subject1, $matches, PREG_OFFSET_CAPTURE);



RE: regex to eliminate port number from url - rtenny - 06-15-2017

If you just want to remove the port number from the URL i would do this

$pattern = "/:[0-9]*/";
$url = preg_replace($pattern, '', $subject1);

even if $subject1 = localhost:8080/index.php it will correctly return localhost/index.php


RE: regex to eliminate port number from url - skunkbad - 06-15-2017

Technically, this is a valid URL:
http://username:[email protected]:8080/one/two/three?legal=:40#:yes

So you are better off parsing it with PHP's parse_url function:



PHP Code:
<?php

$url 
'http://username:[email protected]:8080/one/two/three?legal=:40#:yes';

$parsed_url parse_url$url );

echo 
'<pre>';
print_r$parsed_url );
echo 
'</pre>';

function 
reassemble_without_port$parsed_url )
{
    $url '';

    if( isset( $parsed_url['scheme'] ) )
        $url .= $parsed_url['scheme'] . '://';

    if( isset( $parsed_url['user'], $parsed_url['pass'] ) )
        $url .= $parsed_url['user'] . ':' $parsed_url['pass'] . '@';

    $url .= $parsed_url['host'];

    if( isset( $parsed_url['path'] ) )
        $url .= $parsed_url['path'];

    if( isset( $parsed_url['query'] ) )
        $url .= '?' $parsed_url['query'];

    if( isset( $parsed_url['fragment'] ) )
        $url .= '#' $parsed_url['fragment'];

    return $url;
}

echo 
reassemble_without_port$parsed_url );