2014-03-01 49 views
0

我有一個字符串像評估字符串數組PHP

 "subscription link :%list:subscription% 
     unsubscription link :%list:unsubscription% 
     ------- etc" 

我有一個像

$variables['list']['subscription']='example.com/sub'; 
    $variables['list']['unsubscription']='example.com/unsub'; 
    ----------etc. 

我需要更換%列表中的數組:訂閱%與$變量[ 'list'] ['subscription'],等等 這裏list是第一個索引,而subscription是從$變量 開始的第二個索引。可以使用eval()爲了這個?我沒有任何想法要做到這一點,請大家幫我

回答

2

海峽更換應該在大多數情況下工作:

foreach($variables as $key_l1 => $value_l1) 
    foreach($value_l1 as $key_l2 => $value_l2) 
     $string = str_replace('%'.$key_l1.':'.$key_l2.'%', $value_l2, $string); 

評估和演示叉一個新的PHP的過程,是資源密集型的 - 因此,除非您得到了一些嚴肅的工作,因爲這會削弱你的評價。

除了速度問題,如果代碼的來源來自公共用戶,也可以利用evals。

+0

謝謝,它對我來說工作得很好 – Shin

0

您可以將字符串寫入文件,將該字符串包含在文件中的函數定義中,並給該文件一個.php擴展名。

然後,您將PHP文件包含在當前模塊中,並調用將返回數組的函數。

0

我會使用正則表達式那樣做:

$stringWithLinks = ""; 
$variables = array(); 

// your link pattern, in this case 
// the i in the end makes it case insensitive 
$pattern = '/%([a-z]+):([a-z]+)%/i'; 

$matches = array(); 

// http://cz2.php.net/manual/en/function.preg-replace-callback.php 
$stringWithReplacedMarkers = preg_replace_callback(
    $pattern, 
    function($mathces) { 
     // important fact: $matches[0] contains the whole matched string 
     return $variables[$mathces[1]][$mathces[2]]; 
    }, 
    $stringWithLinks); 

可以很明顯的寫在正確的模式裏面,我只是想使其更清晰。檢查PHP手冊以獲取更多正則表達式可能性我使用的方法是:

http://cz2.php.net/manual/en/function.preg-replace-callback.php