从PHP字符串中删除控制字符 [英] Remove control characters from PHP string

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

问题描述

如何从PHP字符串中删除STX之类的控制字符?我玩过

How can I remove control characters like STX from a PHP string? I played around with

preg_replace("/[^a-zA-Z0-9 .\-_;!:?äÄöÖüÜß<>='\"]/","",$pString)

但是发现它消除了很多方法.有没有一种方法可以删除 only 控制字符?

but found that it removed way to much. Is there a way to remove only control chars?

推荐答案

如果您是用控制字符表示,则第一个32个ascii字符和\x7F (包括回车符等!),那么它将起作用:

If you mean by control characters the first 32 ascii characters and \x7F (that includes the carriage return, etc!), then this will work:

preg_replace('/[\x00-\x1F\x7F]/', '', $input);

(请注意单引号:使用双引号使用\x00会以某种方式导致解析错误.)

(Note the single quotes: with double quotes the use of \x00 causes a parse error, somehow.)

换行符和回车符(通常写为\r\n)可以像这样保存:

The line feed and carriage return (often written \r and \n) may be saved from removal like so:

preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $input);

我必须说,我认为 Bobby的答案是更好,因为 [:cntrl:] 可以更好地传达代码比[\x00-\x1F\x7F]有用.

I must say that I think Bobby's answer is better, in the sense that [:cntrl:] better conveys what the code does than [\x00-\x1F\x7F].

警告:PHP> = 5.3.0中不推荐使用 ereg_replace 已在PHP> = 7.0.0!中删除!,请使用preg_replace而不是ereg_replace:

WARNING: ereg_replace is deprecated in PHP >= 5.3.0 and removed in PHP >= 7.0.0!, please use preg_replace instead of ereg_replace:

preg_replace('/[[:cntrl:]]/', '', $input);

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

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