Reputation: 15
I have a scenario where a user can enter a web address into a text field and I need to return the URI from it.
So a user could potentially enter addresses in the following state of fullness-
http://www.google.co.uk/contoller/function?stuff=thing
www.google.co.uk/controller/function?stuff=thing
google.co.uk/controller/function?stuff=thing
/controller/function?stuff=thing
controller/function?stuff=thing
From all of these examples I would need to return:
/controller/function?stuff=thing
(please note that that the domain could be anything, not just google!)
Upvotes: 1
Views: 213
Reputation: 39385
$arr = array(
'http://www.google.co.uk/contoller/function?stuff=thing',
'www.google.co.uk/controller/function?stuff=thing',
'google.co.uk/controller/function?stuff=thing',
'/controller/function?stuff=thing',
'controller/function?stuff=thing',
);
foreach($arr as $a){
print "/".preg_replace("@https?://.*?(/|$)|[^\s/]+\.[^\s/]+/|^/@", "", $a) . "\n";
}
Upvotes: 1
Reputation: 10638
You can use PHP's parse_url()
for this purpose but this will need the URIs to be in a correct format.
$parsed = parse_url($url);
var_dump( $parsed['path'] . $parsed['query'] );
Will get you the right result as long as the URI starts with http://
(otherwise the domain will be parsed as path as well).
Upvotes: 1