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

前端 未结 3 1672
说谎
说谎 2021-02-10 18:15

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

相关标签:
3条回答
  • 2021-02-10 18:19

    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>
    
    0 讨论(0)
  • 2021-02-10 18:24
    $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>';
    
    0 讨论(0)
  • 2021-02-10 18:39

    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.

    0 讨论(0)
提交回复
热议问题