tags:

views:

155

answers:

2

I have a textarea form field where users will put URL's separated by a new line. Would it be possible to wrap each line from this textarea field with < li > tags?

So I would need the output from the field to be something like this:

<li>some.url.com</li>
<li>some.url.com</li>
<li>some.url.com</li>
<li>some.url.com</li>
<li>some.url.com</li>

Does anyone know who to achive this with PHP please?

+2  A: 
$textareaData = '<li>'.str_replace("\n","</li>\n<li>",trim($textareaData,"\n")).'</li>';

EDIT

Modified to get rid of all blank lines as well:

$textareaData = '<li>'.str_replace(array("\r","\n\n","\n"),array('',"\n","</li>\n<li>"),trim($textareaData,"\n\r")).'</li>';
Mark Baker
@mark my thoughts exactly
Chris
Thanks Mark this works great. If I could just somehow omit empty lines as well it would be perfect!
Johannes
Thank you! Works perfectly. Very much appreciated!!
Johannes
A: 

Using a regular expression you can check for non-empty lines as part of your test:

$li_text = preg_replace('/^(.+)$/', '<li>$1</li>', $_POST['textarea']);

That way if the user has an extra new line at the end of their input (or anywhere inside) you won't get extra empty list items.

SoapBox
This would be great but can't get it to work.It doesn't put the li tags to anything coming from the textarea but hardcoded data works.Btw I got the content coming from the textarea as a variable if that makes a difference.
Johannes
Update: it works fine if there is only 1 line of text in the textarea. If there are more than 1 line it doesn't add any li tags.
Johannes