0

我有一个名为的数组$posts,我像这样运行了一个 foreach

foreach ($posts as $post => $content) {

    $find    = array('~\[image="(https?://.*?\.(?:jpg|jpeg|gif|png|bmp))"\](.*?)\[/image\]~s');
    $replace = array('<img src="$1" alt="" /><p>$2</p>');
    $content = preg_replace($find, $replace, $content);

    }

我现在需要做的是保存$content到与以前相同的索引处的相同数组中,我该怎么做?

请注意,我的数组有几个字段,如 ID、作者、内容、标题和日期。

4

2 回答 2

4

通过引用传递:

foreach ($posts as $post =>  & $content) {

    $find    = array('~\[image="(https?://.*?\.(?:jpg|jpeg|gif|png|bmp))"\](.*?)\[/image\]~s');
    $replace = array('<img src="$1" alt="" /><p>$2</p>');
    $content = preg_replace($find, $replace, $content);

    }
于 2013-08-20T18:14:56.823 回答
1
foreach($post as $post => $content) {
    .... stuff happens here ...
    $posts[$post] = $content;
}

另一种方法是使用参考:

foreach($post as $post => &$content) {
    ... stuff happens here ...
}

$content但是不鼓励使用这种代码,因为如果您稍后在同一范围内重新使用该变量,它可能会导致非常讨厌的意外副作用。

于 2013-08-20T18:15:49.920 回答