汚い文字列を入力しています (句読点の直前に大量のスペース、改行、および余分な偽スペースが含まれています。
私の希望する出力は、以下のコードで説明されています。
余分な空白を削除し、句読点の直前のスペースを削除することができるようです。しかし、私の出力にはまだ不要な余分な改行があります。
ユーザー入力をMySQL dbから画面に出力する際に、以下の関数を使用します。
echo "\t\t".'<p>'.nl2br(convert_str(htmlspecialchars($comment))).'</p>'."\r\n";
私のカスタム関数コードは以下の通りです:
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
//did not worked for me --> preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\n\n", $str);
$str = preg_replace('/[ \t]+/', ' ', preg_replace('/\s*$^\s*/m', "\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;
}
訂正していただけますか?
更新: 準備済みステートメントを使用してユーザー入力を MySQL db テーブルに入力し、db への入力中にユーザーのデータを操作しません。