1

如果存在,我需要\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

4

2 回答 2

2

您将需要使用trim()字符串函数来处理此问题。

trim — 从字符串的开头和结尾去除空格(或其他字符)

例子:

$str = trim($str);
于 2013-04-10T06:56:21.383 回答
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 功能(例如string trim ( string $str [, string $charlist = " \t\n\r\0\x0B" ] )

于 2013-04-10T06:56:03.710 回答