Blood_Wolf89
Blood_Wolf89

Reputation: 45

Tough str_replace, replace parts of result from sql

I am trying to pull data from an sql table and make it so images will display. I have images for each value in the table.

RAW Data from the database:

["NVGoggles"|"ItemMap"|"ItemCompass"|"ItemWatch"|"ACE_CharliePack_ACU_Medic"|"Binocular"|"ACRE_PRC148_ID_2"|"ACRE_PRC343_ID_7"|"CZ805_B_GL_ACR"]

It is an Inventory from a game.

I want to make it so each item will be an image.

I have tried this:

$wea = str_replace('["', '<img src="admin/images/thumbs/', $row["wea"]) & str_replace('"|"', '.png</img><br><img src="admin/images/thumbs/', $row["wea"]) & str_replace('"]', '.png</img>', $row["wea"]);

and I have tried

$wea = str_replace('["', '<img src="admin/images/thumbs/', $row["wea"]);
$wea2 = str_replace('"|"', '.png</img><br><img src="admin/images/thumbs/', $wea);
$wea3 = str_replace('"]', '.png</img>', $wea2);

Does anybody know how I can do this?

Upvotes: 1

Views: 51

Answers (2)

u_mulder
u_mulder

Reputation: 54841

As I said you can get items as an array with:

explode('"|"', trim($str, ' []'))

But if you want your way, then proper code would be:

$wea = str_replace('["', '<img src="admin/images/thumbs/', $row["wea"]);
$wea2 = str_replace('"|"', '.png" /><br><img src="admin/images/thumbs/', $wea);
$wea3 = str_replace('"]', '.png" />', $wea2);

as a proper html img tag is:

<img src="admin/images/thumbs/file.jpg" />

Also str_replace can replace multiple values in one call:

$wea = str_replace(
    array('["', '"|"', '"]'),
    array(
        '<img src="admin/images/thumbs/',
        '.png" /><br><img src="admin/images/thumbs/',
        '.png" />',
    ),
    $row['wea']
);

Upvotes: 2

Ja͢ck
Ja͢ck

Reputation: 173582

It almost looks like JSON encoding, so you could apply a little trick to turn it into an array:

$items = json_decode(strtr($row["wea"], '|', ','), true);
$result = array_map(function($item) { 
    return sprintf('<img src="admin/images/thumbs/%s.png">', $item);
}, $items);

Upvotes: 4

Related Questions