douchenzhan3050 2012-07-17 23:37
浏览 72
已采纳

剥离PHP标签preg_replace

I want to remove all php tags from a external text so it can be included in php safely.

this is the sample input:

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

or any other possibilites

and output:

<html>
</html>

the last php open tag may not have an end tag!

  • 写回答

2条回答 默认 最新

  • douketangyouzh5219 2012-07-17 23:52
    关注

    The proper way to do this is to not include it, but instead load it as a string, using file_get_contents(). That will preserve the PHP tags without executing them. However, the following regex will do exactly what you asked for:

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

    Here's a breakdown of what that string represents:

    #       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.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题