在项目清理期间保留空格和换行字符


Remain spaces and newline chars during article sanitization

我尝试创建类似于消毒文章函数的东西。我指的是一个清除或规范html博客网站中显示的文章内容的功能。

它必须删除除'n之外的所有空白。换行符和空格也是如此。

我开始了一个想法,通过addcslasmsphp函数对换行符和空格进行编码。然后删除所有出现的空白。然后使用条纹斜杠。然后将多个'h事件替换为单个事件。因此,它将类似于换行符和空格,用于regex操作的临时休眠。

但我没有成功,因为输出中没有输入中存在的换行符。

联机版本https://ideone.com/I4oZCJ

我的代码不起作用:

<?php
    $text = 'first line
second line';
    $text = addcslashes($text, "'x20't");
    $text = preg_replace('/'s+/', ' ', $text);
    $text = stripslashes($text);
    $text = preg_replace('/'s+/', ' ', $text);
    var_dump($text);

如何获取?

感谢

您可以使用'S类替换水平空白字符:

preg_replace('/'h+/', ' ', $text');

演示

或者,您可以创建自己的字符类,排除不想替换的所有字符:

 preg_replace('/[^'S'n]+/', ' ', $text);

基本上,这匹配所有非'n(非空白(和非CCD_6(无换行符(的字符。两者都有效。

https://ideone.com/hJrH8R

<?php
function clean($text) {
    $text = preg_replace('/['cK'f'r'x85]+/', '', $text);
    $text = preg_replace('/'h+/', ' ', $text);
    return  $text;
}