How to remove line breaks with PHP or JS

前端 未结 4 930
臣服心动
臣服心动 2021-01-14 20:31

I\'ve tried about everything to delete some extra \\n characters in a web application I\'m working with. I was hoping someone has encountered this issue before

相关标签:
4条回答
  • 2021-01-14 21:03

    Both of the PHP functions you tried return the altered string, they do not alter their arguments:

    $result = preg_replace("[\n]","",$result);
    
    $result = str_replace("\n","",$result);
    
    0 讨论(0)
  • 2021-01-14 21:12

    In javascript, the .replace() method doesn't modify the string. It returns a new modified string, so you need to reference the result.

    text = text.replace(/\n/g,"")
    
    0 讨论(0)
  • 2021-01-14 21:14

    Strangely, using

    str_replace(array('\r','\n'), '', $string)
    

    didn't work for me. I can't really work out why either.

    In my situation I needed to take output from the a WordPress custom meta field, and then I was placing that formatted as HTML in a javascript array for later use as info windows in a Google Maps instance on my site.

    If I did the following:

    $stockist_address = $stockist_post_custom['stockist_address'][0];
    $stockist_address = apply_filters( 'the_content', $stockist_address);
    $stockist_sites_html .= str_replace(array('\r','\n'), '', $stockist_address);
    

    This did not give me a string with the html on a single line. This therefore threw an error on Google Maps.

    What I needed to do instead was:

    $stockist_address = $stockist_post_custom['stockist_address'][0];
    $stockist_address = apply_filters( 'the_content', $stockist_address);
    $stockist_sites_html .= trim( preg_replace( '/\s+/', ' ', $stockist_address ) );
    

    This worked like a charm for me.

    I believe that usage of \s in regular expressions tabs, line breaks and carriage returns.

    0 讨论(0)
  • 2021-01-14 21:20

    In php, use str_replace(array('\r','\n'), '', $string).

    I guess the problem is you also have \r's in your code (carriage returns, also displayed as newlines).

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