0

I'd like to be able to extract certain aspects of a URL, based on a pattern:

http://www.mywebsite.com/{type}-for-sale-in-{district}/{id?}

In this case, I need to be able to extract the parts within the curly braces above. This was inspired by Laravel routing, and will always be the pattern.

Initially I was thinking of somehow doing this with .htaccess, but I'd rather just process the values right on the page with PHP.

dcolumbus
  • 9,596
  • 26
  • 100
  • 165
  • Did someone seriously vote to close my question within 5 seconds of posting it? Unbelievable. – dcolumbus Dec 17 '15 at 21:22
  • The code I've tried previously doesn't work at all, so it's pointless. I honestly have no idea how to do this and just need help from the community to get me going in the right direction. And the question isn't obvious? – dcolumbus Dec 17 '15 at 21:24
  • Some culprit there, who vote negative and we can't see it who is doing that – jewelhuq Dec 17 '15 at 21:25
  • can't you split the data with - then part[0] is for type – jewelhuq Dec 17 '15 at 21:26
  • .htaccess or `mod_rewrite` can definitely handle this URL – anubhava Dec 17 '15 at 21:51
  • 2
    I just got here and I'm voting to close. Question is too broad, states arbitrary constraints without explanation or justification and does not exhibit any attempt to solve the problem – symcbean Dec 17 '15 at 22:02

1 Answers1

1
$uri = trim($_SERVER['REQUEST_URI'], '/');
if(preg_match("#^(?P<type>\w+)-for-sale-in-(?P<district>\w+)(/(?P<id>\d+))?$#i",
              $uri, $matches)
{
  var_dump($matches['type']);
  var_dump($matches['district']);
  if(isset($matches['id']))
    var_dump($matches['id']);
}

Demo here.

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136