-1

http://www.example.com/hu/link

Using PHP how can I only keep the hu? Please note that the link is only one variable, it may be anything

EnexoOnoma
  • 8,454
  • 18
  • 94
  • 179
  • 1
    This isn't clear - are you talking about parsing the url to extract the path segments? Or a redirect of some kind? – Dan Smith Feb 20 '15 at 13:36
  • @Bulk Yes, parsing it to the path segments. Basically I want to echo the `hu` or any other between the `.com/.../` – EnexoOnoma Feb 20 '15 at 13:37
  • Use `explode()` to split the URL on the `/` characters, then take the 2nd-to-last element of the array. – Barmar Feb 20 '15 at 13:38
  • @Xalloumokkelos This could help you: http://php.net/manual/en/function.parse-url.php – Rizier123 Feb 20 '15 at 13:39

4 Answers4

2

You can use explode

$exploded = explode('/', 'http://www.example.com/hu/link');
$value = $exploded[3];
Erbureth
  • 3,378
  • 22
  • 39
Taursus
  • 101
  • 5
0

One solution is this:

$split = explode("/", $_SERVER["REQUEST_URI"]);
echo $split[1];
Kolja
  • 860
  • 4
  • 10
  • 30
0
$url = "http://www.example.com/hu/link";

$split_url = explode('/', $url);
echo $split_url[3];

Output:

hu
mhall
  • 3,671
  • 3
  • 23
  • 35
-1

You can use a regular expression preg_match like this:

$url = 'http://www.example.com/hu/link';
preg_match('/.*www.*\/(.*)\//i',$url, $matches);
print_r($matches[1]);
Kheshav Sewnundun
  • 1,236
  • 15
  • 37
Marco
  • 1
  • 2
  • The reason I downvoted. **1)** There is a parse error. **2)** What if the URL doesn't include the www.? There will be no match. **3)** It's "over-engineering" when you can just `explode()`, albeit a nice alternative. – ʰᵈˑ Feb 20 '15 at 13:45