Search code examples
regexurlurinumeric

How to grab a numeric id in URI?


I need to grab the first numeric ID after #/. For example, I would like only grab 68 and 112 in these URI:

//www.domain.tld/category/14-457-myproduct.html#/68-attribute-fm_300_224_39_b

//www.domain.tld/category/36-578-myproduct.html#/112-attribute-fm_489_471_51_w

I even tried to split the URI in several steps, but it does not work once on my site (Smarty template).


Solution

  • Have you tried something like this :

    <?php
    
    $pattern = "/#\/([0-9])*-/";
    $url1  = "//www.domain.tld/category/14-457-myproduct.html#/68-attribute-fm_300_224_39_b";
    $url2 = "//www.domain.tld/category/36-578-myproduct.html#/112-attribute-fm_489_471_51_w";
    
    echo getNumber($url1, $pattern);
    echo "\n";
    echo getNumber($url2, $pattern);
    
    function getNumber($url, $pattern){
        preg_match($pattern,  $url, $matches);
    
        return substr($matches[0], 2, -1);
    }