user5181531 user5181531 - 6 months ago 10
PHP Question

Need to replace param from string dynamically

Here is My function which helps me to generate links. So here in construct i am getting data from database. Now i want to generate links from db records like

http://localhost/myCrm/my_module/edit/3/1
I know it will need string replace but i am stucked at how to do it ??

function getLinks(array $Links, bool $actions = true)
{
$data = $this->data;

/* $data will look like this.
But it will vary on because this function will be used
over different schema to generate the links */
// $data = ['id'=>'1', 'module_id' => '3', 'item_id' => '1'];

$action = "";

if($actions && $Links)
{
foreach ($Links as $key => $value)
{
$url = "";
// $url = "i need url replaced with the key defined in '{}' from $data[{key}] "

$action .= '<a href="'.$url.'" >'.$value['text'].'</a>';
}
}
}



$Links = [
[
'text' => 'Edit'
'url' => base_url('my_module/edit/{module_id}/{item_id}')
]
];


any help appreciated.

Answer

In this case you will need to use preg_replace_callback function. In preg_replace_callback you can pass closure and make effective changes by getting matches. you can get match from $matches passed in closure

//Your code will look like this
if($actions && $Links)
{
    foreach ($Links as $key => $value)
    {
        $url = preg_replace_callback(

            "/(?:\{)([a-zA-Z0-9_]+)(?:\})/",

            function($matches) use($data)
            {
                return $data[$matches[1]];
            },

            $value['url']
        );

        $action .= '<a href="'.$url.'" >'.$value['text'].'</a>';
    }
}

in this regex (?:\{) represents non capturing group. It means that match will be performed but it will not be captured. so it will match the module_id and item_id from the string so you can get the index here and replace with your data.