从PHP中删除UTF-8字符串中的控制字符 [英] Removing control characters from a UTF-8 string in PHP

查看:107
本文介绍了从PHP中删除UTF-8字符串中的控制字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在客户端删除控制字符(tab,cr,lf,\v和所有其他隐形字符)(输入后),但由于客户端不可信,我必须在服务器中删除它们。

So I am removing control characters (tab, cr, lf, \v and all other invisible chars) in the client side (after input) but since the client cannot be trusted, I have to remove them in the server too.

所以根据这个链接 http://www.utf8-chartable。 de /

控制字符从x00到1F,从7F到9F。
因此我的客户端(javascript)控件字符删除功能是:

the control characters are from x00 to 1F and from 7F to 9F. thus my client (javascript) control char removal function is:

return s.replace(/[\x00-\x1F\x7F-\x9F]/g, "");

我的php(服务器)控制字符删除功能是:

and my php (server) control char removal function is:

$s = preg_replace('/[\x00-\x1F\x7F-\x9F]/', '', $s);

现在这似乎会产生国际utf8字符的问题,例如PHP中的ς(xCF x82)(因为x82在第二个序列组内,所以javascript等价物不会产生任何问题。

Now this seems to create problems with international utf8 chars such as ς (xCF x82) in PHP only (because x82 is inside the second sequence group), the javascript equivalent does not create any problems.

现在我的问题是,我应该将控制字符从7F移到9F吗?据我所知,从127到159(7F到9F)的序列显然可以是有效的UTF-8字符串的一部分吗?

Now my question is, should I remove the control characters from 7F to 9F? To my understanding those the sequences from 127 to 159 (7F to 9F) obviously can be part of a valid UTF-8 string?

也许我甚至不应该过滤00到31个控制字符,因为这些字符中的一些也可以出现在一些奇怪的(日语?中文?)但是有效的utf-8字符?

also, maybe I shouldn't even filter the 00 to 31 control characters because also some of those characters can appear in some weird (japanese? chinese?) but valid utf-8 characters ?

推荐答案

似乎我只需要将 u 标志添加到正则表达式
,因此它变为:

it seems that I just need to add the u flag to the regex thus it becomes:

$s = preg_replace('/[\x00-\x1F\x7F-\x9F]/u', '', $s);

这篇关于从PHP中删除UTF-8字符串中的控制字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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