It is necessary to replace the parameter from the string dynamically

Here is my function that helps me create links. So, here in the design, I get data from the database. Now I want to generate links from db entries, such as http://localhost/myCrm/my_module/edit/3/1I know that string replacement will be required, but I'm stuck on how to do this.

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.

+4
source share
1 answer

In this case, you will need to use the function preg_replace_callback. In preg_replace_callbackyou can go through the closure and make effective changes by getting matches. you can get a match from $ matches held in close

//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>';
    }
}

(?:\{) . , , . module_id item_id, .

+4

All Articles