How to wrap each new line in textarea with li tags? PHP

*爱你&永不变心* 提交于 2019-12-04 13:48:00

问题


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?


回答1:


$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>';



回答2:


And what about something like this

echo preg_replace('/^(.+)(\s*)$/m', '<li>$1</li>', $text);

Output will be anything like this (not nice, but usefull):

<li>dsadsa
</li>
<li>dsdsa
</li>
<li>dsadsad
</li>
<li>dsadsadsad
</li>
<li>vcxvxcvxvcxvcx
</li>
<li>fdsfdsfdsfs
</li>



回答3:


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.



来源:https://stackoverflow.com/questions/3487531/how-to-wrap-each-new-line-in-textarea-with-li-tags-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!