Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How extract part of an URL in PHP to remove specific part?

Tags:

regex

url

php

So, I have this URL in a string:

http://www.domain.com/something/interesting_part/?somevars&othervars

in PHP, how I can get rid of all but interesting_part?

like image 622
null Avatar asked May 20 '10 11:05

null


People also ask

How can I split a string by URL in PHP?

<? php $url = 'http://www.example.com/news?q=string&f=true&id=1233&sort=true'; $values = parse_url($url); $host = explode('. ',$values['host']); echo $host[1]; ?>

How do I part a URL in PHP?

parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it. It parse an URL and return an associative array which contains its various components. parse_str() Function: The parse_str() function is used to parse a query string into variables.

How can I get the last part of a URL in PHP?

Get Last URL Segment If you want to get last URI segment, use array_pop() function in PHP.

Which command will extract the domain suffix in PHP?

Which command will extract the domain suffix? PHP's parse_url function makes it easy to extract the domain, path and other useful bits of information from a full URL.


3 Answers

...

$url = 'http://www.domain.com/something/interesting_part/?somevars&othervars';
$parts = explode('/', $url);
echo $parts[4];

Output:

interesting_part
like image 121
Sarfraz Avatar answered Oct 16 '22 15:10

Sarfraz


Try:

<?php
$url = 'http://www.domain.com/something/interesting_part/?somevars&othervars';

preg_match('`/([^/]+)/[^/]*$`', $url, $m);
echo $m[1];
like image 36
Kamil Szot Avatar answered Oct 16 '22 16:10

Kamil Szot


You should use parse_url to do operations with URL. First parse it, then do changes you desire, using, for example, explode, then put it back together.

$uri = "http://www.domain.com/something/interesting_part/?somevars&othervars";
$uri_parts = parse_url( $uri );

/*
you should get:
 array(4) {
  ["scheme"]=>
  string(4) "http"
  ["host"]=>
  string(14) "www.domain.com"
  ["path"]=>
  string(28) "/something/interesting_part/"
  ["query"]=>
  string(18) "somevars&othervars"
}
*/

...

// whatever regex or explode (regex seems to be a better idea now)
// used on $uri_parts[ "path" ]

...

$new_uri = $uri_parts[ "scheme" ] + $uri_parts[ "host" ] ... + $new_path ... 
like image 5
Ondrej Slinták Avatar answered Oct 16 '22 16:10

Ondrej Slinták