Daniel Schönherr
Daniel Schönherr

Reputation: 235

How to remove multiple newlines (\n) from json string?

It seems to be a problem with magic quotes. The original string just contains \n and \n\n and \n\n\n and \n\r and so on. These newlines arent interpreted by the browser.

What we wanna do is: to replace more than 2 newlines with just 1 single \n.

What we tried yet: a lot of different regular expressions with preg_replace, but the \n wont be kicked out.

Any ideas?

Heres an example (updated on your suggestions - but still not working):

echo '<h3>Source:</h3>';
$arr_test = array(
    'title'     => 'my title',
    'content'   => 'thats my content\n\n\n\nwith a newline'
);
$json_text = json_encode($arr_test);
$json_text = stripslashes($json_text);  //if I leave that out, then \\n will echo
echo $json_text;
// OUTPUT: {"title":"my title","content":"thats my content\n\n\n\nwith a newline"}

echo '<h3>Result 1:</h3>';
$pattern = '/\n{2,}/';
$result1 = preg_replace($pattern,"x",$json_text);
echo $result1;
// OUTPUT: {"title":"my title","content":"thats my content\n\n\n\nwith a newline"}

echo '<h3>Result 2:</h3>';
$result2 = preg_replace( '/([\n]+)/s', 'x', $json_text, -1, $count );
echo $count;
// OUTPUT: 0
echo $result2;
// OUTPUT: {"title":"my title","content":"thats my content\n\n\n\nwith a newline"}

Upvotes: 1

Views: 7166

Answers (5)

Sascha Goerting
Sascha Goerting

Reputation: 26

You could also try looping through the string and replace two newlines with one until no double newline is left:

echo '<h3>Result 4:</h3>';
$result4 = $json_text;
do{
    $result4 = str_replace('\n\n','\n',$result4, $count);
}while($count>0);

echo $result4;
// OUTPUT: {"title":"my title","content":"thats my content\nwith a newline"}

or with preg_replace:

echo '<h3>Result 5:</h3>';

$result5 = preg_replace('/(\\\n)+/m', '\\\n', $json_text);

echo $result5;
// OUTPUT: {"title":"my title","content":"thats my content\nwith a newline"}

Upvotes: 1

safarov
safarov

Reputation: 7804

if(get_magic_quotes_gpc()) {
   $string =  stripslashes($string); // $string sended with POST or GET 
}

$string = str_replace("\n\n", "\n", $string); // only for 2 newlines

OR

$string = preg_replace('/\n{2,}/s', '\n', $string); // more than 2 newlines

Upvotes: 1

Ravi Jethva
Ravi Jethva

Reputation: 2031

echo str_replace("\n", "", "aassasa\n \n aasassf \n saaaaafs asaf ssaf \n afsf \n ");

just for your demo

echo str_replace("a","","aaabcefefgaaaaaaaaaaamnopqraaaaaa");

Upvotes: 0

Chris Gessler
Chris Gessler

Reputation: 23113

Try this:

  1. Replace all \n characters (1 or more) with \n
  2. /s modifier - include multiple lines
>     $string = preg_replace( $'/([\n]+)/s', '\n', $string, -1, $count );                                               
>     echo $count;

Upvotes: 0

web-nomad
web-nomad

Reputation: 6003

try this:

// replace 2 or more consecutive newlines with a single newline
$string = preg_replace("/\n\n+/i", "\n", $string);

Upvotes: 0

Related Questions