Convert comma separated string into list [closed]

我怕爱的太早我们不能终老 提交于 2019-12-23 06:15:31

问题


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

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