Search code examples
phppreg-replacestr-replaceereg-replace

PHP preg_replace -####/


I'm back again to show my ignorance once more.

I need assistance grabbing numbers that are in a URL in a specific spot. The rest of the URL may also contain numbers so I need to restrict it to grabbing the numbers from just one location, for example:

http://www.example.com/99-Kittens-1382/animals

I had been using ereg_replace to grab all the numbers but then realized:
1) ereg_replace is deprecated
2) Some URLs may have numbers in them elsewhere.

So in this case I ended up with 991382 instead of just the 1382 that I wanted.

The URL structure should always be that we have -####/ so I think we should be able to match based off of that. (dash, four numbers, forward slash)

I've always been terrible with regular expression matching. Can anyone help me out?


Solution

  • This is probably better done without the complication of regex:

    $urlParts = parse_url($str);
    $pathParts = explode('/', $urlParts['path']);
    $firstParts = explode('-', $pathParts[1]);
    $numberYouWant = array_pop($firstParts);
    

    See it working