0

I have an array called $posts which i ran a foreach on like this

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);

    }

what i need to do now is to save $content into the same array at the same index as before, how can i do that?

Note that my array has several fields like Id, Author, content, title & date.

0

2 Answers 2

4

Pass by reference:

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);

    }
Sign up to request clarification or add additional context in comments.

6 Comments

Clever, I would have done: $posts[$post] = $content, but I like this better.
I output the array inside my view and get 0 difference, it's exactly the same as it is in the database after i added the & before $content.
@SamPettersson: try doing a print_r($content); outside the foreach.
@AmalMurali Returns what's inside the database.
@SamPettersson: there's a difference between the two.
|
1
foreach($post as $post => $content) {
    .... stuff happens here ...
    $posts[$post] = $content;
}

The alternative is to use a reference:

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

but this sort of code is discouraged, because it can lead to very nasty unexpected side effects later if you happen to re-use the $content varaible later in the same scope.

1 Comment

This seems to scramble all the data, the output just becomes "{"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.