2

假设我有一个确定以 开头的文本块,我<?php如何从原始文本中提取第一个 php 代码块?

示例文本:

<?php

echo "uh oh... \"; ?> in a \"; // string...  ?>";
echo 'uh oh... \\\'; ?> in a /* string ?> */...';

// ?> nope not done

/*

?> still not done

*/

echo "this should be echoed too";

?>

this is even more text...

我想我需要使用 PHP 核心函数token_get_all,但我不知道如何使用它来获取 PHP 块的大小以从原始字符串中删除。该函数显然知道它何时到达 PHP 块的末尾。我不能只将所有文本传递给 PHP,因为这在许多其他处理层中很深。

所以,最终结果应该让我在包含以下内容的 PHP 块末尾之外的字符串:(带有任何前面的空格)

this is even more text...

以及在不同字符串中解析出的 PHP 代码:

<?php

echo "uh oh... \"; ?> in a string...";
echo 'uh oh... \\\'; ?> in a string...';

// ?> nope not done

/*

?> still not done

*/

echo "this should be echoed too";

?>

你可以这样做:

<?php
$code = <<<'PHP'
<?php

echo "uh oh... ?> in a string...";
echo 'uh oh... ?> in a string...';

// ?> nope not done

/*

?> still not done

*/

echo "this should be echoed too";

?>

this is even more text...
PHP;

function findPHPBlockEnd($code_text) {
    $tokens = token_get_all($code_text);

    $current_character = 0;
    foreach ($tokens as $current_token) {
        $current_character += is_string($current_token)
                            ? strlen($current_token)
                            : strlen($current_token[1]);

        if (is_array($current_token) && $current_token[0] === T_CLOSE_TAG) {
            // End of block.
            break;
        }
    }

    return $current_character;
}

$end = findPHPBlockEnd($code);
$code_block = substr($code, 0, $end);
var_dump($code_block);

这输出:

string(83) "<?php

echo "uh oh... ?> in a string...";
echo 'uh oh... ?> in a string...';

// ?>"

(关闭标签确实在评论中起作用,所以这是预期的行为。)

如果您进行评估$code[$end],您将在之后立即获得该字符?>,但这是 . 的首选行为substr

4

1 回答 1

0

你可以这样做:

<?php
$code = <<<'PHP'
<?php

echo "uh oh... ?> in a string...";
echo 'uh oh... ?> in a string...';

// ?> nope not done

/*

?> still not done

*/

echo "this should be echoed too";

?>

this is even more text...
PHP;

function findPHPBlockEnd($code_text) {
    $tokens = token_get_all($code_text);

    $current_character = 0;
    foreach ($tokens as $current_token) {
        $current_character += is_string($current_token)
                            ? strlen($current_token)
                            : strlen($current_token[1]);

        if (is_array($current_token) && $current_token[0] === T_CLOSE_TAG) {
            // End of block.
            break;
        }
    }

    return $current_character;
}

$end = findPHPBlockEnd($code);
$code_block = substr($code, 0, $end);
var_dump($code_block);

这输出:

string(83) "<?php

echo "uh oh... ?> in a string...";
echo 'uh oh... ?> in a string...';

// ?>"

(关闭标签确实在评论中起作用,所以这是预期的行为。)

如果您进行评估$code[$end],您将在之后立即获得该字符?>,但这是 . 的首选行为substr

于 2013-10-15T22:56:30.177 回答