开发者

Converting line breaks into <li> tags

I'm creating an upload form that has a text area for users to input cooking recipes with. Essentially, what I want to do is wrap each line in a <li> tag for output purposes. I've been trying to manipulate the nl2br function but to no avail. Can anyone help?

I'm retrieving the text area's content via POST and storing entries in a MySQL database. Here's what the code looks like at the moment (the check_input function strips slashes, etc.):

$prep开发者_运维知识库Text=check_input($_POST['preparationText']);    
$cookText=check_input($_POST['cookingText']); 


Explode the string by \n then wrap each line in an li tag.

<?php
$string = "line 1\nline 2\nline3";

$bits = explode("\n", $string);

$newstring = "<ol>";
foreach($bits as $bit)
{
  $newstring .= "<li>" . $bit . "</li>";
}
$newstring .= "</ol>";


Not quite pretty, but an idea that comes to mind is to :

  • explode the string, using newline as a separator
  • and implode the array, using </li><li> between items :

Which could be translated to something like this :

$new_string = '<li>' . implode('</li><li>', explode("\n", $old_string)) . '</li>';

(Yeah, bad idea -- don't do that, especially if the text is long)


Another solution, way cleaner, would be to just replace the newlines in your string by </li><li> :
(wrapping the resulting string inside <li> and </li>, to open/close those)

$new_string = '<li>' . str_replace("\n", '</li><li>', $old_string) . '</li>';

With that idea, for example, the following portion of code :

$old_string = <<<STR
this is
an example
of a 
string
STR;

$new_string = '<li>' . str_replace("\n", '</li><li>', $old_string) . '</li>';
var_dump($new_string);

Would get you this kind of output :

string '<li>this is</li><li>an example</li><li>of a </li><li>string</li>' (length=64)


I created a function based on Richard's answer in case it saves anyone some time!

/**
 * @param string $str - String containing line breaks
 * @param string $tag - ul or ol
 * @param string $class - classes to add if required
 */
function nl2list($str, $tag = 'ul', $class = '')
{
    $bits = explode("\n", $str);

    $class_string = $class ? ' class="' . $class . '"' : false;

    $newstring = '<' . $tag . $class_string . '>';

    foreach ($bits as $bit) {
        $newstring .= "<li>" . $bit . "</li>";
    }

    return $newstring . '</' . $tag . '>';
}


function nl2li($str)
{
    if (!isset($str)) return false;
    $arr = explode("\r\n", $str);
    $li  = array_map(function($s){ return '<li>'.$s.'</li>'; }, $arr);
    return '<ul>'.implode($li).'</ul>';
}

Input:

Line 1\r\nLine2\r\nLine3\r\n

Output:

<ul><li>Line 1</li><li>Line 2</li><li>Line 3</li></ul>


The simplest way to do it:

function ln2ul($string) {
  return '<ul><li>' . str_replace("\n", '</li><li>', trim($string)) . '</li></ul>';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜