2013-04-10 67 views
1

如果存在,我需要刪除\r\n\r\n在字符串的最開始和/或最後。php正則表達式 - 刪除 r n r n在最開始和最後一個字符串

我的問題是我無法實現我的目標代碼如下。

//if exists, remove \r\n\r\n at the very beginning 
$str = preg_replace('/^(\r\n\r\n)/', '', $str); 

//if exists, remove \r\n\r\n at the very end 
$str = preg_replace('/$(\r\n\r\n)/', '', $str); 

也許我的html輸出的源代碼視圖可以給你一些線索。我不知道原因,但<br />標籤不是並排的。他們的位置是一個一個在另一個之下。

<br /> 
<br /> 
some text 
... 
... 
some text<br /> 
<br /> 

還在下面,我分享我的整個字符串操作代碼。我有問題的2行代碼是以下代碼的一部分。 (除了上述2行代碼以外的其他部分效果良好)

function convert_str ($str) 
{ 
    // remove excess whitespace 
    // looks for a one or more spaces and replaces them all with a single space. 
    $str = preg_replace('/ +/', ' ', $str); 
    // check for instances of more than two line breaks in a row 
    // and then change them to a total of two line breaks 
    $str = preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\r\n\r\n", $str); 
    //if exists, remove \r\n\r\n at the very beginning 
    $str = preg_replace('/^(\r\n\r\n)/', '', $str); 

    //if exists, remove \r\n\r\n at the very end 
    $str = preg_replace('/$(\r\n\r\n)/', '', $str); 

    //if exists, remove 1 space character just before any \r\n 
    $str = str_replace(" \r\n", "\r\n", $str); 
    //if exists, remove 1 space character just after any \r\n 
    $str = str_replace("\r\n ", "\r\n", $str); 
    // if exists; remove 1 space character just before punctuations below: 
    // $punc = array('.',',',';',':','...','?','!','-','—','/','\\','「','」','‘','’','"','\'','(',')','[',']','’','{','}','*','&','#','^','<','>','|'); 
    $punc = array(' .',' ,',' ;',' :',' ...',' ?',' !',' -',' —',' /',' \\',' 「',' 」',' ‘',' ’',' "',' \'',' (',')',' [',' ]',' ’',' {',' }',' *',' &',' #',' ^',' <',' >',' |'); 
    $replace = array('.',',',';',':','...','?','!','-','—','/','\\','「','」','‘','’','"','\'','(',')','[',']','’','{','}','*','&','#','^','<','>','|'); 
    $str = str_replace($punc,$replace,$str); 
    return $str; 
} 

請問您能糾正我嗎?

感謝

BR

+2

你知道[**修剪**]( http://php.net/manual/en/function.trim.php)對不對? – elclanrs 2013-04-10 06:55:14

+0

@elclanrs我錯誤的堅持使用preg_replace讓我盲目,我認爲,直到修剪提到的答案。我感到羞愧。非常感謝。你的評論對我來說是一個很好的教訓。 – 2013-04-10 07:03:07

+0

也使用正則表達式的字符串,這很容易是非常糟糕的! – ITroubs 2013-04-10 07:03:30

回答

2

您將需要使用trim()字符串函數來處理此問題。

飾邊 - 從字符串的開頭和末尾地帶空格(或其它字符)

實施例:

$str = trim($str); 
+3

剛剛[trim()'](http://php.net/manual/en/function.trim.php)怎麼樣? – Phil 2013-04-10 06:57:59

0

嘗試更換

//if exists, remove \r\n\r\n at the very end 
$str = preg_replace('/$(\r\n\r\n)/', '', $str); 

通過

//if exists, remove \r\n\r\n at the very end 
$str = preg_replace('/(\r\n\r\n)$/', '', $str); 

您也可以嘗試使用Trim function(例如字符串修剪(字符串$海峽[ ,字符串$ charlist =「\ t \ n \ r \ 0 \ x0B」])

相關問題