How to clear a file with php code from special characters (opening and closing tags)

The task is actually elementary at first glance, but in the file itself, string constants, for example, can contain these characters, for example.

That’s actually the whole question. Thanks in advance for the solutions.

Answer 1, authority 100%

You can do this:

$code = preg_replace('/<\?(?:php)?|\?>/i','',$code);

This removes all <?, <?phpand ?>from the text.

The same, but with the usual replacement:

$code = str_replace( array('<?php','<?','?>'), '', $code );

Answer 2

$tokens = token_get_all(file_get_contents(__FILE__));
$output = '';
foreach ($tokens as $token) {
    if (!is_array($token)) {
        $output .= $token;
    switch ($token[0]) {
        case T_OPEN_TAG:
        case T_CLOSE_TAG:
            $output .= $token[1];

Answer 3

In a word, without waiting for the help of experts, I ground something like this.

$code =

If you have more elegant ideas, I will be glad to help.