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;
}

訂正していただけますか?

ありがとう

ブラジル

4

2 に答える 2

2

これを処理するには、 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 に答える