2013-04-10 70 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”])

相关问题