-3

I have the following url : http:example.com/country/France/45. With the pattern http:example.com/country/name/**NUMBER**(?$_GET possibly).

How can I extract the number with a regex (or something else then regex) ?

Kalzem
  • 7,320
  • 6
  • 54
  • 79

6 Answers6

3

With regexp:

$str = 'http:example.com/country/France/45';
preg_match('/http:example\.com\/country\/(?P<name>\w+)\/(?P<id>\d+)/', $str, $matches);
print_r($matches); // return array("name"=>"France", "id" => 45);
nicowernli
  • 3,250
  • 22
  • 37
2
$url = 'http:example.com/country/France/45';
$id  = end(explode('/',trim($url,'/')));

Simple isn't ?

The usage of trim () is to remove trailing \

shatheesh
  • 633
  • 6
  • 10
2
echo $last = substr(strrchr($url, "/"), 1 );

strrchr() will give last occurence of the / character and then substr() gives string after it.

halkujabra
  • 2,844
  • 3
  • 25
  • 35
1

use something like this

    $url = "http://example.com/country/France/45";
    $parts = explode('/', $url);
    $number = $parts[count($parts) - 1];

and if you have GET variable at the end, you can explode further like this

    $number = explode('?', $number);
    $number = $number[0];

hope this helps :)

Milan Maharjan
  • 4,156
  • 1
  • 21
  • 28
-2

Use explode():

$parts = explode('/', $url);
$number = $parts[count($parts)-1];
Barmar
  • 741,623
  • 53
  • 500
  • 612
-2

the get command for php is $_GET so to show to number do

<html>
<body>
<?php
echo $_GET["eg"];
?>
</body>
</html>

with a URL of http:example.com/country/name/?eg=**NUMBER**