Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

regex - Remove control characters from PHP string

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

preg_replace("/[^a-zA-Z0-9 .-_;!:?????üü?<>='"]/","",$pString)

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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-x1Fx7F]/', '', $input);

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

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

preg_replace('/[x00-x09x0Bx0Cx0E-x1Fx7F]/', '', $input);

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

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...