'POSIX-like shell variable expansion in PHP

Is there a function or module in PHP that can perform shell expansion on strings like how a POSIX shell does it? I'm looking for something that allows the following pseudocode (or similar) to work:

$vars= (
    "greeting" => "hello", 
    "noun" => "12 bacons", 
    "leave" => "goodbye" );
$str = '${greeting}, human, I’m here to ${verb:-save} your world.';
$str2= magic_function($str, $vars);
printf($str);
// hello, human, I'm here to save your world.
// ^ vars['greeting'] set
//                           ^ vars['verb'] not set, replacement is used

Tried searching on the internet but most of what I found was how to invoke full shells (subprocessess) rather that simply imitating the syntax of one component. I'm also not sure it's possible to export arbitrary variables into a system() call?

I don't need the full POSIX functionality, but covering at least set/unset replacements, as well as basic pattern replacement (eg.: ${var##pattern}) would be nice. As for PHP versions, anything that works in 7.x, 8.x works for me.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source