NoChecksum NoChecksum - 1 year ago 108
PHP Question

Find position of console escape code in string

tl;dr How do I write

strpos($haystack, '^[[H^[[2J')
in PHP?

A linux command line app delivers a screen-full of data followed by a console escape code to return the cursor to the "home" position in a regular loop. To access the data I piped the output to my own script like so:

$ ./otherapp | php myscript.php

It's a continuous stream of data so I use this example for non-blocking stream consumption.

Now to decode the output I need to grab a full frame/screen full of data. The escape codes are shown in nano as
. The easiest way seems to be detecting these escape codes and using the output between them.

How are the escape codes represented in a PHP string? Can I use
(or mbstring equivalent) to detect their position?

Answer Source

It seems you're on a Unix environment. To achieve what your escape codes do, you can try with echo -en "\033[H" and echo -en "\033[2J", so I guess you should try something like strpos('\033[H\033[2J', $haystack).

Maybe you'll need to add an extra backslash ('\\033[H\\033{2J').

Since \033 means "the byte with octal value 33", which is ESC, this should work:

strpos("\e[H\e[2J", $haystack)

You need to enclose it in double-quotes (") if you want PHP to interpret escape sequences for special characters.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download