假设我有一个以<?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";
?>
发布于 2013-10-15 14:56:30
你可以这样做:
<?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
的首选行为。
https://stackoverflow.com/questions/19391899
复制