JohnPep
JohnPep

Reputation: 193

PHP get full url from two strings

Guys I have two Strings

$first = "/calvin/master/?p=pages&id=3";   //DYNAMIC URL

$second = "http://localhost/calvin/";      //BASE URL USER DECIDED

I want to get full url like this

$target = "http://localhost/calvin/master/?p=pages&id=3";   //FULL URl

How can I do it.. Please note that, the directory calvin can change according to where user decides, he/she can even place script in child directories. eg. instead of calvin can be myweb/scripts/this_script

Upvotes: 1

Views: 93

Answers (3)

Ashish Choudhary
Ashish Choudhary

Reputation: 2034

You can use:

$target = $second . str_replace(parse_url($second)['path'], '', $first);

parse_url will break the $second URL to obtain the path after the domain which is directory calvin in this case. We can then replace the path in the $first to remove duplicate directory path. and then can append the remaining $first path without the directory to the $second path with the directory.

Upvotes: 0

Nirnae
Nirnae

Reputation: 1345

This might be what you're trying to do :

<?php


$first = "/calvin/master/?p=pages&id=3";
$second = "http://localhost/calvin/";

//First we explode both string to have array which are easier to compare
$firstArr = explode('/', $first);
$secondArr = explode('/', $second);

//Then we merged those array and remove duplicata
$fullArray = array_merge($secondArr,$firstArr);
$fullArray = array_unique($fullArray);

//And we put all back into a string
$fullStr = implode('/', $fullArray);
?>

Upvotes: 2

online Thomas
online Thomas

Reputation: 9381

$first_array =split("/" , $first);
$second_array =split("/" , $second);

$url = $second; //use the entire beginning

if($second_array[count($second_array) - 1] == $first_array[0]) { //check if they are the same
    for ($x = 1; $x <= count($first_array); $x++) { //add parts from the last part skipping the very first part
       $url .= "/" .$first_array[$x];
    }
}

Upvotes: 0

Related Questions