Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.):

$prepText=check_input($_POST['preparationText']);    
$cookText=check_input($_POST['cookingText']); 
like image 754
Luis Avatar asked Mar 23 '11 12:03

Luis


3 Answers

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>";
like image 87
Richard Parnaby-King Avatar answered Sep 29 '22 15:09

Richard Parnaby-King


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 . '>';
}
like image 43
Friendly Code Avatar answered Sep 29 '22 15:09

Friendly Code


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)
like image 45
Pascal MARTIN Avatar answered Sep 29 '22 15:09

Pascal MARTIN