Isolating part of url with php

I would like to highlight a specific part of the url if the structure remains the same:

ex. URL - http://www.URL.co.uk/87/318/carrot_cake/

this is 318 part of the above example, however the number can range from 1 to 999999 but will always stay between 2 x '/' and to the left of the name (carrot_cake in the example), this is where I'm strugling.

Thank you in

+2


source to share


2 answers


This should work:

<?php
$url = 'http://www.URL.co.uk/87/318/carrot%5Fcake/';
$id = explode('/', $url);
echo $id[5];
?>

      



Update : corrected code and tested

+5


source


If you want Moff's answer, use it as it's simpler. If it doesn't, would it help?

<?php
  if (preg_match  ('/^//\d+//(\d+)//.*/', parse_url($url, PHP_URL_PATH), $results)) {
    print_r($results);      
  }
?>

      



(My local PHP installation is broken right now, so I hope the syntax is correct.)

+2


source







All Articles