Question

Let's say you have two urls.

http://testing.org/directory/index.php/arg1/arg2
Array ( [scheme] => http [host] => testing.org [path] => /directory/index.php/arg1/arg2 ) 

Or something like this:

http://testing.org/index.php/arg1/arg2
Array ( [scheme] => http [host] => testing.org [path] => /index.php/arg1/arg2 ) 

I know you can break the url down with parse_array(). When I do that, the path is everything after 'testing.org'. In the first example path variable 1 in the array is 'directory' but in the second example path variable 1 is 'index.php'.

I am trying to figure out hot to do 2 separate things. Firstly remove everything after index.php but I keep fumbling the ball. Also, how would I remove the '/directory/' from the first url?

But I'd also like to learn how replace a section of the path too.

Was it helpful?

Solution

You can use a combination of parse_url() and regex to accomplish this. The below regular expression will strip out everything after the index.php in the URL path.

$parts = parse_url($url);
$scriptname = preg_replace('#(index\.php)/.*#', '$1', $parts['path']);
$result = $parts['scheme'].'://'. $parts['host'] . $scriptname;

For the two URLs given the question, the output would be as follows:

http://testing.org/directory/index.php
http://testing.org/index.php

Demo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top