Skip to content Skip to sidebar Skip to footer

How To Remove Line Breaks With Php Or Js

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 and knows what can be

Solution 1:

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).

Solution 2:

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,"")

Solution 3:

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);

Solution 4:

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.

Post a Comment for "How To Remove Line Breaks With Php Or Js"