我试着创建像sanitize文章函数这样的东西。我指的是清理或标准化显示在html博客网站上的文章内容的功能。
它必须删除除\n和之外的所有空格。换行符和空格。
我开始使用addcslashes php函数来编码换行符和空格。然后删除所有出现的空格。然后使用带斜杠。然后将多个\x20实例替换为单个实例。因此,它类似于换行符和空格,用于正则表达式操作的临时休眠。
但我没有成功,因为输出中没有输入中确实存在的换行符。
我的代码不起作用:
<?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);如何获得它?
谢谢
发布于 2016-06-30 01:01:26
您可以使用\h类替换水平空格字符:
preg_replace('/\h+/', ' ', $text');或者,您可以创建自己的字符类,排除所有不想替换的字符:
preg_replace('/[^\S\n]+/', ' ', $text);基本上,这匹配所有非\S (非空格)和非\n (无换行符)的字符。这两种方法都有效。
发布于 2016-06-30 07:08:53
<?php
function clean($text) {
$text = preg_replace('/[\cK\f\r\x85]+/', '', $text);
$text = preg_replace('/\h+/', ' ', $text);
return $text;
}https://stackoverflow.com/questions/38105819
复制相似问题