问题
I have a string eg:
$string = "word1,word2,word3,word4";
I need to echo this into <li>
elements using PHP. So $string
becomes:
<li>word1</li>
<li>word2</li>
<li>word3</li>
<li>word4</li>
回答1:
Like this:
$string = "word1,word2,word3,word4";
$string = explode(",",$string);
foreach ($string as $str) {
echo "<li>".$str."</li>";
}
You can explode()
the string into an array, loop through it, and output the results into a list option.
回答2:
Try this:
echo "<li>" . str_replace ("," , "</li><li>" , $string) . "</li>";
For what you are trying to accomplish, the explode approach adds unnecessary overhead.
回答3:
You may try this
$string = "word1,word2,word3,word4";
echo "<ul>";
foreach(explode(',', $string) as $li) {
echo "<li>$li</li>";
}
echo "</ul>";
DEMO.
来源:https://stackoverflow.com/questions/19728572/convert-comma-separated-string-into-list