UTF 8字符串删除除换行符以外的所有不可见字符 [英] UTF 8 String remove all invisible characters except newline

查看:628
本文介绍了UTF 8字符串删除除换行符以外的所有不可见字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下正则表达式从UTF-8字符串中删除所有不可见的字符:

I'm using the following regex to remove all invisible characters from an UTF-8 string:

$string = preg_replace('/\p{C}+/u', '', $string);

这可以正常工作,但是如何更改它以除去除换行符之外的所有不可见字符?我用[^ \ n]等尝试了一些东西,但这没用.

This works fine, but how do I alter it so that it removes all invisible characters EXCEPT newlines? I tried some stuff using [^\n] etc. but it doesn't work.

感谢您的帮助!

换行符为'\ n'

推荐答案

使用双重否定":

$string = preg_replace('/[^\P{C}\n]+/u', '', $string);

说明:

  • \P{C}[^\p{C}]相同.
  • 因此[^\P{C}]\p{C}相同.
  • 由于我们现在有了一个否定的字符类,因此可以从中减去其他字符,例如\n.
  • \P{C} is the same as [^\p{C}].
  • Therefore [^\P{C}] is the same as \p{C}.
  • Since we now have a negated character class, we can substract other characters like \n from it.

这篇关于UTF 8字符串删除除换行符以外的所有不可见字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆