• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
regex to eliminate port number from url

#1
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);
Reply

#2
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
On the package it said needs Windows 7 or better. So I installed Linux.
Reply

#3
Technically, this is a valid URL:
http://username:[email protected]=: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 ); 
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2017 MyBB Group.