1

i prefer jquery.

let's say i have a string with ,

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>

1
  • please clarify question, you want this output to the page? is jQuery handling this string? Or is PHP doing it? Commented Nov 4, 2009 at 21:59

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

how to implement it in html/php file?
2

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

Comments

2

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;

Comments

0

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

1 Comment

I think you may need to put the callback function as the first argument? array_map('makeLiTag', $items);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.