Skip to content

Instantly share code, notes, and snippets.

@marekkalnik
Created February 13, 2012 14:55
Show Gist options
  • Save marekkalnik/1817419 to your computer and use it in GitHub Desktop.
Save marekkalnik/1817419 to your computer and use it in GitHub Desktop.
nl2li
<?php
/**
* Converts elements divided by newline characters to list items
* @param String $text
* @param Array $htmlAttrs
*/
function nl2li($text, array $htmlAttrs = null) {
if (!empty($htmlAttrs)) {
$attributes = array_walk($htmlAttrs, function($key, $value) {
return $key.' = "'.$value.'"';
});
$openingLi = '<li '.implode(' ', $attributes).'>';
}
else
{
$openingLi = '<li>';
}
$parsedText = '';
$token = strtok($text, "\n");
while($token !== false) {
$parsedText .= $openingLi.$token.'</li>'.PHP_EOL;
$token = strtok("\n");
}
return $parsedText;
}
@laurentb
Copy link

from os import linesep

def nl2li(text, html_attrs = None):
    html_attrs = html_attrs or dict()
    add = ' '.join(['%s="%s"' % (k, v) for k, v in html_attrs.iteritems()])
    openli = '<li%s%s>' % (' ' * min(len(add), 1), add)
    closeli = '</li>'
    return linesep.join(['%s%s%s' % (openli, line, closeli)
                        for line in text.splitlines()])

def test():
    """
    Prove the superiority of Python.
    Just run nosetests on the file.
    """
    assert nl2li('') == ''
    assert nl2li('coucou\nhehehe').splitlines() == \
            ['<li>coucou</li>', '<li>hehehe</li>']
    assert nl2li('coucou\nhehehe', {'class': 'plop'}).splitlines() == \
            ['<li class="plop">coucou</li>', '<li class="plop">hehehe</li>']

This could be better, but it's still more readable :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment