How to create Ul list from string?
i prefer jquery.
let's say i have a string wi开发者_如何学Goth ,
adam, lisa, john, sarah
and i want to turn them into :
<ul><li>Adam</li><li>lisa</li><li>john</li><li>sarah</li></ul>
"<ul><li>" + "adam, lisa, john, sarah".split(", ").join("</li><li>") + "</li></ul>"
[Edit:] I assumed javascript since you mentioned jQuery. I don't know the best way to do it in php, but you do the same as above using preg_split
and implode
in php.
Using jQuery's $.map function:
var names = 'adam,lisa,john,sarah';
var html = '<ul>'+$.map(names.split(','), function(name){
return '<li>'+name+'</li>'
}).join('')+'</ul>';
Or you could do explode and foreach:
$array = explode(', ','adam, lisa, john, sarah');
foreach ($array as $name) {
$output .= '<li>' . $name . '</li>';
}
echo '<ul>' . $output . '</ul>';
Maybe a little simpler.
EDIT: Even easier would be a regular str_replace.
$list = '<ul><li>' . str_replace(', ','</li><li>','adam, lisa, john, sarah') . '</li></ul>';
echo $list;
To do it in PHP, explode the string to make it into an array and then use array_map to convert each item to a li tag. Once that's done, implode it to get the desired result:
$items = explode( ",", "adam,lisa,john,sarah" );
array_map( "makeLiTag", $items );
echo( "<ul>" . implode( "", $items ) . "</ul>" );
function makeLiTag( &$item, $key )
{
$item = "<li>$item</li>";
}
精彩评论