2011-02-18 80 views
11

我想在數組中的所有項目中進行字符串替換。我擁有的是:字符串替換數組中的所有項目PHP

$row['c1'] = str_replace("&", "&", $row['c1']); 
$row['c2'] = str_replace("&", "&", $row['c2']); 
$row['c3'] = str_replace("&", "&", $row['c3']); 
$row['c4'] = str_replace("&", "&", $row['c4']); 
$row['c5'] = str_replace("&", "&", $row['c5']); 
$row['c6'] = str_replace("&", "&", $row['c6']); 
$row['c7'] = str_replace("&", "&", $row['c7']); 
$row['c8'] = str_replace("&", "&", $row['c8']); 
$row['c9'] = str_replace("&", "&", $row['c9']); 
$row['c10'] = str_replace("&", "&", $row['c10']); 

如何用較少的代碼實現這一目標?我認爲一個foreach聲明會起作用,例如:

$columns = array($row['c1'], $row['c2'], $row['c3'], $row['c4'], $row['c5'], $row['c6'], $row['c7'], $row['c8'], $row['c9'], $row['c10']); 

foreach ($columns as $value){ 
    $value = str_replace("&", "&", $value); 
} 

但它不起作用。

回答

29

只要做到:

$row = str_replace("&", "&", $row); 

注:您的foreach不起作用,因爲你需要一個基準,或使用關鍵:

foreach ($columns as &$value) { // reference 
    $value = str_replace("&", "&", $value); 
} 
unset($value); // break the reference with the last element 

或者:

foreach ($columns as $key => $value){ 
    $columns[$key] = str_replace("&", "&", $value); 
} 

儘管這裏沒有必要,因爲str_replace接受並返回arra YS。

+1

你有它的人...我不知道`str_replace`也接受`陣列`太 – Ish 2011-02-18 18:31:19

2

你應該引用調用它,否則foreach創建的$value

foreach ($columns as &$value)

0

另一種解決辦法重複的副本是用PHP array_walk這樣的:

function custom_replace(&$item, $key) { 
    $item = str_replace('22', '75', $item); 
} 

// Init dummy array. 
$columns = array('Cabbage22', 'Frid22ay', 'Internet', 'Place22', '22Salary', '22Stretch', 'Whale22Inn'); 

// Print BEFORE. 
echo 'Before: '; 
print_r($columns); 

// Make the replacements. 
array_walk($columns, 'custom_replace'); 

// Print AFTER. 
echo 'After:'; 
print_r($columns); 

輸出:

Before: Array 
(
    [0] => Cabbage22 
    [1] => Frid22ay 
    [2] => Internet 
    [3] => Place22 
    [4] => 22Salary 
    [5] => 22Stretch 
    [6] => Whale22Inn 
) 
After: Array 
(
    [0] => Cabbage75 
    [1] => Frid75ay 
    [2] => Internet 
    [3] => Place75 
    [4] => 75Salary 
    [5] => 75Stretch 
    [6] => Whale75Inn 
) 
相關問題