Is there parse_url equivalent or custom parse url function PHP?

1.1k Views Asked by At

I am compressing some CSS and JS files and have few methods that use parse_url to get the url components. Just found out that prior to php 5.3.28 there is no host and my compression function heavily rely on it in order to get the correct paths.

So on php 5.3.28 < I get

Array
(
    [path] => //fonts.googleapis.com/css
    [query] => family=Open+Sans
)

and 5.3.28 >

Array
(
    [host] => fonts.googleapis.com
    [path] => /css
    [query] => family=Open+Sans
)

can anyone post a possible replacement function or the actual 5.3.28 > parse_url or a regex I could work with.

Any help is appreciated.

1

There are 1 best solutions below

0
On

As stated in one of the comments, prior the 5.4.7 version, PHP will not recognize the host part for urls without the scheme. Check parse_url() returns an error when example.com is passed question for a few possible solutions, one of them is to manually add a default scheme, or, you can try this example.

$url = '//fonts.googleapis.com/css?family=Open+Sans';
$url_parts = parse_url( $url );

if ( !isset( $url_parts['host'] ) ) {
    $part = ( isset( $url_parts['path'] ) ? $url_parts['path'] : '' ) . ( isset( $url_parts['query'] ) ? '?' . $url_parts['query'] : '' ) . ( isset( $url_parts['fragment'] ) ? '#' . $url_parts['fragment'] : '' );    
    $host = strstr( $url, $part, true );
    $url_parts['host'] = substr( $host, strpos( $host, '//' ) + 2 );
}