We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Add function "str_replace" to Volt

Hi,

I'm trying to add the PHP function "str_replace" to Volt.

The following code doesn't work and I don't understand why

services.php

$compiler = $volt->getCompiler();
$compiler->addFunction(
  'str_replace',
  function($resolvedArgs, $exprArgs) use ($compiler)
  {
    $firstArgument = $compiler->expression($exprArgs[0]['expr']);
    $secondArgument = $compiler->expression($exprArgs[1]['expr']);
    $thirdArgument = $compiler->expression($exprArgs[2]['expr']);
    return 'str_replace("'.$firstArgument.'", "'.$secondArgument.'", "'.$thirdArgument.'")';
  }
);

test.volt

{{ str_replace("Harris", "Sheldon", "My name is Harris.") }}

Could you help me?

Thank you.



77.7k
Accepted
answer

You can simply specify a string as second argument, which will look for it in the global namespace:

$compiler->addFunction('str_replace','str_replace');


4.3k

Thank you Lajos Bencz, it works.