2016-05-29 63 views
4

這是我的功能,它可以幫助我生成鏈接。所以在這裏構造我從數據庫中獲取數據。現在我想從db記錄生成鏈接,如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

那麼'str_replace'呢? –

+0

它不會在這裏工作,因爲我會從字符串中替換列名稱。 – user5181531

回答

4

在這種情況下,你將需要使用preg_replace_callback功能。在preg_replace_callback中,您可以通過關閉進行有效更改。你可以拿到賽從$比賽中封閉

//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_iditem_id,以便您可以在此處獲取索引並用您的數據替換。

+0

非常感謝你pratik。這正是我想要的。非常感謝你的回答。 – user5181531