如何从字符串中删除PHP代码? [英] How to remove php code from a string?

查看:75
本文介绍了如何从字符串中删除PHP代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含php代码的字符串,我需要从该字符串中删除php代码,例如:

I have a string that has php code in it, I need to remove the php code from the string, for example:

<?php $db1 = new ps_DB() ?><p>Dummy</p>

应返回<p>Dummy</p>

并且没有php的字符串(例如<p>Dummy</p>)应返回相同的字符串.

And a string with no php for example <p>Dummy</p> should return the same string.

我知道可以使用正则表达式来完成此操作,但是4小时后我还没有找到解决方法.

I know this can be done with a regular expression, but after 4h I haven't found a solution.

推荐答案

 <?php
 function filter_html_tokens($a){
    return is_array($a) && $a[0] == T_INLINE_HTML ?
      $a[1]:
      '';
 }
 $htmlphpstring = '<a>foo</a> something <?php $db1 = new ps_DB() ?><p>Dummy</p>';
 echo implode('',array_map('filter_html_tokens',token_get_all($htmlphpstring)));
 ?>


ircmaxell指出:这将需要有效的PHP!


As ircmaxell pointed out: this would require valid PHP!

正则表达式的路由是(不允许在字符串/文件中使用短标签的'php'.没有结束符?>(出于某种原因,Zend推荐这样做?),当然还有一个UNgreedy&DOTALL模式:

A regex route would be (allowing for no 'php' with short tags. no ending ?> in the string / file (for some reason Zend recommends this?) and of course an UNgreedy & DOTALL pattern:

preg_replace('/<\\?.*(\\?>|$)/Us', '',$htmlphpstring);

这篇关于如何从字符串中删除PHP代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆