1

我正在输入一个脏字符串(在标点符号之前有很多空格、换行符和额外的假空格。

我想要的输出在下面的代码中进行了解释。

似乎我可以删除多余的空格 + 删除标点符号之前的空格。但是我的输出仍然有多余的换行符。

我在将用户输入从 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 数据库表中,并且在进入数据库期间我不操作用户的数据。

4

1 回答 1

2

我发现了一个简单但耗时 5 小时的原因:使用 just\n而不是\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
    $str = preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\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;
}
于 2013-04-09T15:46:20.297 回答