PHP 从字符串中删除终端代码 [英] PHP remove terminal codes from string
问题描述
在处理使用 proc_open
创建的进程的输入/输出时,我遇到了特殊的终端 ANSI 代码 (\033[0J
,\033[13G
),除了没有找到这些特定代码正在做什么的参考之外,它们真的搞乱了我的 preg_match
调用.
While processing the input/output of a process created with proc_open
, I've been hit with the special terminal ANSI codes (\033[0J
,\033[13G
), aside from not finding a reference to what these particular codes are doing, they are really messing with my preg_match
calls.
PHP 是否有内置的方法来清理这些类型的字符串?或者与 preg_replace
一起使用的正确表达式是什么?请注意,我正在处理非 ascii 字符,因此剥离除...之外的所有内容都不起作用.
Does PHP have a built in method for cleansing these types of strings? Or what would be the correct expression to use with preg_replace
? Please note, I am dealing with non ascii characters, so stripping everything except... will not work.
推荐答案
通常 ANSI 代码是由 ESC (\033
aka \x1b
) 引入的,一个空心方块括号,然后是数字(可能重复:*[32;40m
)并以字母结尾.
Usually ANSI codes are introduced by an ESC (\033
aka \x1b
), an open square bracket, then numbers (possibly repeated: *[32;40m
) and terminated by a letter.
你可以使用类似 #\\x1b[[][0-9]+(;[0-9]*)[A-Za-z]#
到 preg_replace
他们都被遗忘了.
You can use something like #\\x1b[[][0-9]+(;[0-9]*)[A-Za-z]#
to preg_replace
them all to oblivion.
这有效(刚刚测试),即使绝对是矫枉过正:
This works (just tested), even if definitely overkill:
$test = preg_replace('#\\x1b[[][^A-Za-z]*[A-Za-z]#', '', $test);
I've also found this on GitHub, and this on SO.
这篇关于PHP 从字符串中删除终端代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!