问题
$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