如果存在,我需要删除\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
你知道[**修剪**]( http://php.net/manual/en/function.trim.php)对不对? – elclanrs 2013-04-10 06:55:14
@elclanrs我错误的坚持使用preg_replace让我盲目,我认为,直到修剪提到的答案。我感到羞愧。非常感谢。你的评论对我来说是一个很好的教训。 – 2013-04-10 07:03:07
也使用正则表达式的字符串,这很容易是非常糟糕的! – ITroubs 2013-04-10 07:03:30