James
James

Reputation: 43677

Get number from an url

We have an url like http://site.com/people/593765-barack-obama?sort=popular

How do I get only the ID part of the link? It is 593765 for this example.

So the pattern is http://site.com/people/{somenumber}-{anythingelse}

I'm not sure how to get it by using regex.

Upvotes: 0

Views: 109

Answers (5)

mtf
mtf

Reputation: 101

You will need to filter it from

/shots/593765-brainzap?list=following

which is the $_SERVER['REQUEST_URI'] of the page.

Upvotes: 0

h2ooooooo
h2ooooooo

Reputation: 39550

Use regex:

/people\/([0-9]+)\-/

<?php
    //$pattern = $_SERVER['REQUEST_URI'];
    $pattern = "http://site.com/people/593765-barack-obama?sort=popular";
    preg_match('/people\/([0-9]+)\-/', $pattern, $match);
    if (isset($match[1])) {
        echo "The number is: " . $match[1];
    }
?>

Upvotes: 1

Leonov Mike
Leonov Mike

Reputation: 923

Regex pattern:

#/(\d+)-.+\??#

Usage example:

preg_match('#/(\d+)-.+\??#', 'http://site.com/people/593765-barack-obama?sort=popular', $matches);
var_dump($matches[1]);

Output:

string(6) "593765"

Upvotes: 1

flowfree
flowfree

Reputation: 16462

preg_match('#/(\d+)-#', $url, $m);
echo $m[1]; // 593765

Upvotes: 3

Parcye
Parcye

Reputation: 98

I guess shorts is a 'catch' file for the URL, and the {somenumber}-{anythinelse} is a parameter you obtain, I would just explode the parameter.

list($iNumber, $sAnything) = explode("-", $sParam1);

Upvotes: 1

Related Questions