替换多个换行符,制表符和空格

| 我想用一个换行符替换多个换行符,并用一个空格替换多个空格。 我尝试
preg_replace(\"/\\n\\n+/\", \"\\n\", $text);
失败了! 我也在$ text上进行格式化工作。
$text = wordwrap($text, 120, \'<br/>\', true);
$text = nl2br($text);
$ text是从用户那里获取的用于BLOG的大文本,为了获得更好的格式,我使用了自动换行。     
已邀请:
        从理论上讲,您的正则表达式确实可以工作,但是问题是,并非所有操作系统和浏览器都仅在字符串末尾发送\\ n。许多人还会发送\\ r。 尝试: 我简化了这个:
preg_replace(\"/(\\r?\\n){2,}/\", \"\\n\\n\", $text);
并解决仅发送\\ r的问题:
preg_replace(\"/[\\r\\n]{2,}/\", \"\\n\\n\", $text);
根据您的更新:
// Replace multiple (one ore more) line breaks with a single one.
$text = preg_replace(\"/[\\r\\n]+/\", \"\\n\", $text);

$text = wordwrap($text,120, \'<br/>\', true);
$text = nl2br($text);
    
           使用\\ R(代表任何行结束序列):
$str = preg_replace(\'#\\R+#\', \'</p><p>\', $str);
在这里找到:用段落标签替换两行 有关Escape序列的PHP文档:   \\ R(换行符:匹配\\ n,\\ r和\\ r \\ n)     
        根据我的理解,这就是答案:
// Normalize newlines
preg_replace(\'/(\\r\\n|\\r|\\n)+/\', \"\\n\", $text);
// Replace whitespace characters with a single space
preg_replace(\'/\\s+/\', \' \', $text);
这是我用来将新行转换为HTML换行符和段落元素的实际功能:
/**
 *
 * @param string $string
 * @return string
 */
function nl2html($text)
{
    return \'<p>\' . preg_replace(array(\'/(\\r\\n\\r\\n|\\r\\r|\\n\\n)(\\s+)?/\', \'/\\r\\n|\\r|\\n/\'),
            array(\'</p><p>\', \'<br/>\'), $text) . \'</p>\';
}
    
        您需要multiline修饰符来匹配多行:
preg_replace(\"/PATTERN/m\", \"REPLACE\", $text);
同样在您的示例中,您似乎正好用2个换行符替换了2个以上的换行符,这并不是您的问题所表明的。     
        我尝试了以上所有方法,但对我而言不起作用。然后我创建了解决该问题的长途之路... 之前:
echo nl2br($text);
之后:
$tempData = nl2br($text);
$tempData = explode(\"<br />\",$tempData);

foreach ($tempData as $val) {
   if(trim($val) != \'\')
   {
      echo $val.\"<br />\";
   }
}
它对我有用。我在这里写这是因为,如果有人来这里找到像我这样的答案。     
        我建议这样的事情:
preg_replace(\"/(\\R){2,}/\", \"$1\", $str);
这将处理所有Unicode换行符。     
        如果只想用一个标签替换多个标签,请使用以下代码。
preg_replace(\"/\\s{2,}/\", \"\\t\", $string);
    
        尝试这个:
preg_replace(\"/[\\r\\n]*/\", \"\\r\\n\", $text); 
    
        更换字符串或文档的开头和结尾!
preg_replace(\'/(^[^a-zA-Z]+)|([^a-zA-Z]+$)/\',\'\',$match);
    
        我已经在PHP中处理了strip_tags函数,遇到了一些问题,例如:换行后出现带有空格的新行,然后新换行连续出现...等。没有任何规则:(。 这是我处理strip_tags的解决方案 将多个空格替换为一个,将多个换行符替换为单个换行符
function cleanHtml($html)
{
    // Clean code into script tags
    $html = preg_replace(\'#<script(.*?)>(.*?)</script>#is\', \'\', $html);

    // Clean code into style tags
    $html = preg_replace(\'/<\\s*style.+?<\\s*\\/\\s*style.*?>/si\', \'\', $html );

    // Strip HTML
    $string = trim(strip_tags($html));

    // Replace multiple spaces on each line (keep linebreaks) with single space
    $string = preg_replace(\"/[[:blank:]]+/\", \" \", $string); // (*)

    // Replace multiple spaces of all positions (deal with linebreaks) with single linebreak
    $string = preg_replace(\'/\\s{2,}/\', \"\\n\", $string); // (**)
    return $string;
}
关键字是(*)和(**)。     

要回复问题请先登录注册