我想用一个换行符替换多个换行符,用一个空格替换多个空格。
我尝试了preg_replace("/'n'n+/", "'n", $text);
,但失败了!
我还对$text进行格式化。
$text = wordwrap($text, 120, '<br/>', true);
$text = nl2br($text);
$text是从BLOG用户那里获取的一个大文本,为了更好地格式化,我使用了wordwrap。
理论上,正则表达式确实有效,但问题是并非所有操作系统和浏览器都只在字符串末尾发送。许多人还会发送''r。
尝试:
我简化了这个:
preg_replace("/('r?'n){2,}/", "'n'n", $text);
并且只解决某些发送的问题:
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(换行符:匹配''R''n、''R''n和''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>';
}
您需要多行修饰符来匹配多行:
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_tag的解决方案
将多个空格替换为一个,将多个换行符替换为单个换行符
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;
}
关键字是(*)和(**)。