Alvaro Louzada
Alvaro Louzada

Reputation: 433

Get part of a dynamic url

I'm trying to get a part of the URL on my website

In this situation:

http://mywebsite/filexx/yyyyy/abaete/374    

$url2 = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

if(preg_match("/\/(\d+)$/",$url2,$matches))
{
    $meuid = $matches[1];
}

its works, but lets put 2 different situations:

http://mywebsite/filexx/yyyyy/abaete/374/?p=1
// i'm try to get the 374 (ID)

http://mywebsite/filexx/yyyyy/374/?p=1
// here the same

so I want to get last part if integer ( 374 ) or the part before the query 374/?p=1. So I want the 374.

Thanks.

Upvotes: 1

Views: 1139

Answers (3)

user1467267
user1467267

Reputation:

I'll just make my comment an answer:

<?php
    $string = 'http://mywebsite/filexx/yyyyy/abaete/374/?g=123';
    $matches = array();

    preg_match_all('/.*?\/(\d+)\/?/s', $string, $matches);

    echo '<pre>';
    print_r($matches);
    echo '</pre>';
?>

It will also ignore the /?getval1=1&getval2=2&etc=etc

Output

Array
(
    [0] => Array
        (
            [0] => http://mywebsite/filexx/yyyyy/abaete/374/
        )

    [1] => Array
        (
            [0] => 374
        )

)

Upvotes: 1

Teaqu
Teaqu

Reputation: 3263

http://mywebsite/filexx/yyyyy/abaete/374    

$url2 = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

if(preg_match('~([0-9]+)\/\?p=~', $url2, $matches))
{
    $meuid = $matches[1];
}

This gets the numbers before /?p=.

Upvotes: 0

Baronth
Baronth

Reputation: 989

$url = 'http://mywebsite/filexx/yyyyy/abaete/374/?p=1';

$explodedUrl = explode('/',$url);
$countArray = count($explodedUrl);
if(strpos($explodedUrl[$countArray-1],'?') === FALSE){
    $yourId = $explodedUrl[$countArray-1];
} else {
    $yourId = $explodedUrl[$countArray-2];
}

$yourId contains your Id

Upvotes: 0

Related Questions