Search code examples
phpregexsmartysubstrstrpos

Smarty strpos and substr to get text after last forward slash in URL


After lots of searching this is the closest I got. I'm using {$smarty.server.REQUEST_URI} to get second part of the URL after http. Naturally am ending up with lots of text1/text2/text3. Now I'm after extracting last string of text located after the last forward slash.

from my understanding I have to use strpos to get the position of the last forwardslash, ideally start from the end and stop on the first slash which in reality would be the last since we started right-to-left, and then use substr to get anything from that strpos onwards.


Solution

  • You can do it this way (if you using Smarty2):

    {assign var="dirs" value="/"|explode:$smarty.server.REQUEST_URI}
    {math equation ="x-y" x=$dirs|@count y=1 assign="last"}
    {$dirs[$last]}
    

    and this way:

    {assign var="dirs" value="/"|explode:$smarty.server.REQUEST_URI}
    {$dirs[$dirs|@count-1]}
    

    if you are using Smarty 3