How to remove line breaks with PHP or JS

前端 未结 4 969
臣服心动
臣服心动 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条回答
  •  旧时难觅i
    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.

提交回复
热议问题