2016-05-16 174 views
3

我有包含這些值的數據陣列:如何用數組中的字符串替換子字符串使用preg_replace? (PHP)

Array 
(
    [id] => 1 
    [myid] => 9 
    [date] => 2014-01-30 
    [user] => 17 
    [reason] => some text here... 
) 

這串包含數字參照數據數組索引:

$columns = '(0) as "id",(1) as "myid",(2) as "date",(3) as "user",(4) as "reason"'; 

是否有可能改變封閉在數字括號,包括括號從數組中取適當的值?

我知道如何與(string) preg_replace((array) $patterns, (array) $replacements, (string) $subject)一起工作,但完全不知道如何解決這個問題。

理想的結果字符串看起來是這樣的:

'1' as "id",'9' as "myid",'2014-01-30' as "date",'17' as "user",'some text here...' as "reason" 
+0

看看[array_walk()](http://php.net/manual/en/function.array-walk.php)或[array_reduce()](http://php.net) /manual/en/function.array-reduce.php)構建一個單一的字符串。 –

+0

你爲什麼要這樣的結果?它是爲了什麼? –

+0

爲什麼你需要改變字符串,爲什麼不從數組中新的字符串? –

回答

2

使用preg_replace_callbackstr_replace功能的解決方案:

$columns = '(0) as "id",(1) as "myid",(2) as "date",(3) as "user",(4) as "reason"'; 

// $arr is your initial array 
$result = preg_replace_callback(
       "/(\(\d\)) as \"(\w+?)\",?/i", 
       function ($maches) use($arr){ 
        return str_replace([$maches[1]], "'". $arr[$maches[2]]. "'", $maches[0]); 
       }, 
       $columns); 

print_r($result); 

輸出:

'1' as "id",'9' as "myid",'2014-01-30' as "date",'17' as "user",'some text here...' as "reason" 
+0

謝謝。我接受你的問題,因爲我認爲這是最好的答案。儘管如此,弗雷恩在評論中的建議是我目前的解決方案。 –

+1

是的,如果您正在處理真實代碼(生產),Frayne的建議將非常合理。但是我已經將解決​​方案作爲當前「抽象」測試案例的解決方案。無論如何,謝謝 – RomanPerekhrest

+0

這很棒,我也使用一些PHP庫函數做出答案。 –

0

只需使用一個循環與str_replace函數。遍歷數組,使用括號中的循環索引作爲搜索字符串,並將其替換爲相應的值。

0

array_flip是你的救星

直接從文檔

<?php 
$input = array("oranges", "apples", "pears"); 
$flipped = array_flip($input); 

print_r($flipped); 
?> 

上面的例子將輸出:

Array 
(
    [oranges] => 0 
    [apples] => 1 
    [pears] => 2 
) 
2

你可以用一個簡單的foreach循環做到這一點:

$info = array(
    'id' => 1, 
    'myid' => 9, 
    'date' => '2014-01-30', 
    'user' => 17, 
    'reason' => 'some text here...' 
); 

$columns = '(0) as "id",(1) as "myid",(2) as "date",(3) as "user",(4) as "reason"'; 

foreach (array_values($info) as $key => $value) { 
    $columns = str_replace(
     '(' . $key . ')', 
     str_pad($value, strlen($value) + 2, "'", STR_PAD_BOTH), 
     $columns 
    ); 
} 

echo $columns; 
+1

如果字符串以'$ columns ='(0)開頭爲「myid」,(1)爲「id」,'? – splash58

+1

哈哈哈,有很多問題,但OP的要求已經解決了。 –

1

你可以只用一些PHP庫函數做到這一點。

$info = array(
    'id' => 1, 
    'myid' => 9, 
    'date' => '2014-01-30', 
    'user' => 17, 
    'reason' => 'some text here...' 
); 

$columns = '(0) as "id",(1) as "myid",(2) as "date",(3) as "user",(4) as "reason"'; 

$new_Arr = array(); 
$column_arr = explode(",", $columns); 
foreach($column_arr as $values){ 
    $arr = explode(" as ", $values); 
    $new_Arr[] = "'".$info[trim($arr[1], '"')]."' as ".$arr[1]; 
} 

echo implode(",", $new_Arr) //'1' as "id",'9' as "myid",'2014-01-30' as "date",'17' as "user",'some text here...' as "reason" 
+0

複雜的方式,但你得到它。 +1 –

+0

@RaviHirani,實際上有一個人使用'str_pad'和'str_replace',另一個人'preg_replace_callback',所以左邊是'foreach'。 –