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']);
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>";
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 . '>';
}
Not quite pretty, but an idea that comes to mind is to :
</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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With