Php - explode a string with two delimiters

送分小仙女□ 提交于 2019-12-14 02:50:15

问题


$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 />";
}

回答1:


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 />';
}



回答2:


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) . "'/>";
}



回答3:


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...




回答4:


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

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


来源:https://stackoverflow.com/questions/24636689/php-explode-a-string-with-two-delimiters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!