如何从json字符串中删除多个换行符(\ n)?

时间:2012-04-03 12:49:44

标签: php json preg-replace newline

这似乎是魔术引号的问题。原始字符串只包含\ n和\ n \ n和\ n \ n \ n和\ n \ r \ n等等。这些换行符不会被浏览器解释。

我们想做的是:用1个单独的\ n来替换2个以上的换行符。

我们尝试了什么:使用preg_replace的许多不同的正则表达式,但是\ n不会被踢掉。

有什么想法吗?

下面是一个例子(更新了你的建议 - 但仍然无效):

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"}

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

你也可以尝试循环遍历字符串并用一个替换两个换行符直到没有留下双换行符:

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"}

或使用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"}

答案 2 :(得分:0)

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

仅适用于您的演示

echo str_replace(“a”,“”,“aaabcefefgaaaaaaaaaaamnopqraaaaaa”);

答案 3 :(得分:0)

试试这个:

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

答案 4 :(得分:0)

试试这个:

  1. 用\ n
  2. 替换所有\ n个字符(1个或多个)
  3. / s修饰符 - 包含多行
  4. >     $string = preg_replace( $'/([\n]+)/s', '\n', $string, -1, $count );                                               
    >     echo $count;