2012-04-03 150 views
1

這似乎是一個魔術引號的問題。原始字符串只包含\ n和\ n \ n和\ n \ n \ n和\ n \ r等等。這些換行符不會被瀏覽器解釋。如何從json字符串中刪除多個換行符( 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"} 
+0

我想你試過第二個正則表達式有第四個字的錯字! (又名:請顯示你的一些工作和結果,所以很容易看出它是表達式中的錯誤還是不同的東西(json中的奇怪東西)) – Nanne 2012-04-03 12:52:21

+0

你試過了什麼?你是否包含/ s修飾符,其中包含新行? – 2012-04-03 12:57:42

回答

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

是啊!真棒!這就像魅力一樣! – 2012-04-03 14:29:02

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 
+0

如果將2替換爲1,那麼有三個時會發生什麼?三到兩個,所以你需要執行兩次替換。 – 2012-04-03 13:01:44

+0

@ChrisGessler帶preg_replace的第二個解決方案可以在不帶/ s修飾符的情況下運行超過2個 – safarov 2012-04-03 13:03:56

+1

,如何超出一行? – 2012-04-03 13:07:49

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

只爲您的演示

回聲str_replace函數( 「A」, 「」,「aaabcefefgaaaaaaaaaaamnopq raaaaaa「);

+0

這不是簡單地用空字符串替換所有\ n字符嗎? – 2012-04-03 12:59:55

+0

它的工作原理請嘗試 – 2012-04-03 13:08:30

+0

當它出現倍數時,它是如何離開1 \ n的?即\ n \ n \ n – 2012-04-03 13:12:34

0

嘗試:

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

嘗試這種情況:

  1. 所有\ n個字符(1或多個)替換爲\ n
  2. /s的改性劑 - 包括多行
>  $string = preg_replace($'/([\n]+)/s', '\n', $string, -1, $count);            
>  echo $count; 
相關問題