user
user

Reputation: 751

Php - explode a string with two delimiters

$string = 'folder1:image1.jpg|folder2:image2.jpg|folder3:image3.jpg';

I need to explode the string to get the following result:

<img src="/folder1/image1.jpg" />
<img src="/folder2/image2.jpg" />
<img src="/folder3/image3.jpg" />

It's not a problem with one delimiter but I have two delimiters and don't know how to do it:

$imagedata = explode("|", $string);
foreach($imagedata as $image) {
echo "$image<br />";
}

Upvotes: 1

Views: 973

Answers (4)

the_tiger
the_tiger

Reputation: 346

If you want to keep it short (but not clear):

 $imagedata = '<img src="/' . implode("\" />\n<img src=\"", str_replace(':', '/', explode("|", $string))) . '" />';

Upvotes: 0

localhost
localhost

Reputation: 89

use this:

$string = 'folder1:image1.jpg|folder2:image2.jpg|folder3:image3.jpg';
$imagedata = explode("|", $string);
foreach($imagedata as $image) {
    $img=explode(":", $image);
    echo '<img src="' . $img[0] . '/' . $img[1] . '" /><br />';
}

Upvotes: 1

Omarchh
Omarchh

Reputation: 1

Maybe you could try with 2 foreach...

$string = 'folder1:image1.jpg|folder2:image2.jpg|folder3:image3.jpg';

$imagedata = explode("|", $string);
foreach($imagedata as $folder) {
    $imageFolders = explode(":", $folder);
    foreach ($imageFolders as $image) {
        echo "$image<br />";
    }
}

Then maybe just need to save it on other variable...

Upvotes: 0

dave
dave

Reputation: 64657

You don't need two delimiters, you can just do a str_replace after you explode:

$imagedata = explode("|", $string);
foreach($imagedata as $image) {
    echo "<img src='/".str_replace(":","/",$image) . "'/>";
}

Upvotes: 5

Related Questions