这是我的功能,它可以帮助我生成链接。所以在构造中我从数据库获取数据。现在我想从像http://localhost/myCrm/my_module/edit/3/1
这样的数据库记录生成链接我知道它需要字符串替换,但我仍然坚持如何做到这一点?
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}')
]
];
任何帮助表示感谢。
答案 0 :(得分:4)
在这种情况下,您需要使用
preg_replace_callback
功能。在preg_replace_callback
中,您可以通过获取匹配来传递闭包并进行有效更改。你可以从封闭传递的$ match中获得匹配
//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
匹配,因此您可以在此处获取索引并替换为您的数据。