Search code examples
phpsmarty

Smarty substr & strpos from last occurrence


{assign var="bar_at" value=$product.supplier_reference|strpos:"="}

The $product.supplier_reference looks like https://www.example.com/search?w=1366&h=610&q=the_actual_reference

I need to get what comes after the last '='(the actual reference)

How to get strpos after the last occurrence?


Solution

  • First of all the right function to go with is : strrpos

    you have various ways to accomplish this:

    1- the pure smarty way:

    {assign var="str" value="https://www.example.com/search?w=1366&h=610&q=the_actual_reference"}
    {assign var="offset" value=$str|strrpos:"="}
    {assign var="reference" value=$str|substr:($offset+1)}
    {$reference}
    

    2- create new plugin in the plugins directory , which lays under the following path : vendor/smarty/smarty/libs/plugins/ , add new file with your new plugin name, lets say function.getReference.php

    create a new function smarty_function_getReference

    and write your pure PHP function, then use this from your smarty template directly like following :

    function  smarty_function_money ($paramters) {
        $url = $paramters['url'];
        // here is our function body
    }
    

    within your smarty template:

    {getReference url="https://www.example.com/search?w=1366&h=610&q=the_actual_reference"}
    

    3- add new modifier:

    where-ever you are defining your smarty view logic register the new modifier :

    $callback = function ($string) {
        // perform your logic within this callback
    };
    
    $this->registerPlugin('modifier', 'getRefernce', $callback);
    

    then call this modifier directly from your smarty template like following :

    {"https://www.example.com/search?w=1366&h=610&q=the_actual_reference"|getRefernce}