difference between two strings and merge [duplicate]

Tag: php , string Author: swx_wataxi Date: 2014-04-23

This question already has an answer here:

Say I have string A: /CI/index.php?/user/dashboard/
And string B: http://localhost/CI/index.php

Using php how does one find the commonality between them aka /CI/index.php and remove it so that we are only left with http://localhost/CI/index.php?/user/dashboard/

Is the common part always the beginning of A and the end of B?
yes, but its not always the same

Other Answer1

The commented link from Mr Bahamondez didn't work for his specific problem.

Is this CodeIgniter? Wouldn't removing 'CI/index.php' with htaccess rewrites be an easier option?

I've hacked this long winded essay of a lump of code together (it's late...) which I hope will help you - I'm sure someone else will do a better job, there's a problem though with getting the question mark back into the url.

$str1 = "http://localhost/CI/index.php";
$str2 = "/CI/index.php?/user/dashboard/";

// Take the url scheme and host out of the equation
$url_array = parse_url($str1 . $str2);

// store the path
$path = $url_array['path'];

// store the query (anything after a ?)
$query = $url_array['query'];

// Combine and split into an array using '/' as delimiter
$segments = explode("/", $path . $query);

// store the unique keys and filter out any empty values
$new_array = array_unique( array_filter($segments) );

var_export($new_array);

Result:

array (
  1 => 'CI',
  2 => 'index.php',
  5 => 'user',
  6 => 'dashboard',
)

Which you could then rebuild with

// Hacky rebuild the url
$segment = "";

foreach ($new_array as $seg) {
    $segment .= $seg . "/";
}

$new_url = $url_array['scheme'] . "://" . $url_array['host'] . "/" . $segment;

Which will give http://localhost/CI/index.php/user/dashboard/

index.php and index.php? causes a problem but if you have a specific case where you know that it will always be /CI/index.php maybe you can hack that out?

comments:

actually, the posted duplicate works fine for my method. but i really appreciate your work and will take it under advisement! upvoted