簡體   English   中英

剝離PHP標簽preg_replace

[英]Strip PHP tags preg_replace

我想從外部文本中刪除所有php標簽,以便可以安全地將其包含在php中。

這是示例輸入:

<?
?>
<html>
<?php ?>
<?= ?>
</html>
<?

或任何其他可能性

並輸出:

<html>
</html>

最后一個php open標簽可能沒有結束標簽!

我認為沒有一種很好的方法可以精確地完成您想要的操作,但是如果可以在輸出中發送PHP標記(未解析),則可以使用:

<?php echo file_get_contents('input.html'); ?>

否則,請看一下token_get_all方法:

http://www.php.net/manual/en/function.token-get-all.php

您可以遍歷所有結果,僅返回T_INLINE_HTML類型的結果:

$toks = token_get_all( file_get_contents( 'input.html' ) );
foreach( $toks as $tok ) {
  if( $tok[0] == T_INLINE_HTML )   {
    print $tok[1];
  }
}

正確的方法是不包含它,而是使用file_get_contents()其作為字符串加載。 這將保留PHP標記而不執行它們。 但是,以下正則表達式將完全滿足您的要求:

#<\?.*?(\?>|$)#s

這是該字符串代表的細分:

#       A delimiter marking the beginning and end of the expression - nearly anything will do (preferably something not in the regex itself)
<\?      Find the text "<?", which is the beginning of a PHP tag.  Note that a backslash before the question mark is needed because question marks normally do something special in regular expressions.
.*?     Include as much text as necessary (".*"), but as little as possible ("?").
(\?>|$)  Stop at an ending PHP tag ("?>"), OR the end of the text ("$").  This doesn't necessarily have to stop at the first one, but since the previous part is "as little as possible", it will.
#       The same delimiter, marking the end of the expression
s       A special flag, indicating that the pattern can span multiple lines.  Without it, the regex would expect to find the entire PHP tag (beginning and end) on a single line.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM