如何从字符串中删除php代码?

如何从字符串中删除php代码?,php,preg-replace,Php,Preg Replace,我有一个包含php代码的字符串,我需要从字符串中删除php代码,例如: <?php $db1 = new ps_DB() ?><p>Dummy</p> 虚拟 应该返回虚拟 没有php的字符串,例如Dummy应该返回相同的字符串 我知道这可以用正则表达式来完成,但4小时后我还没有找到解决方案。如果您使用的是PHP,您只需要使用正则表达式来替换与PHP代码匹配的任何内容 以下语句将删除PHP标记: preg_replace('/^<\?php.*\?\&

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

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

应该返回
虚拟

没有php的字符串,例如
Dummy

应该返回相同的字符串


我知道这可以用正则表达式来完成,但4小时后我还没有找到解决方案。

如果您使用的是PHP,您只需要使用正则表达式来替换与PHP代码匹配的任何内容

以下语句将删除PHP标记:

preg_replace('/^<\?php.*\?\>/', '', '<?php $db1 = new ps_DB() ?><p>Dummy</p>');
preg_替换(“/^/”,“Dummy

”);
如果未找到任何匹配项,则不会替换任何内容。


 <?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

正则表达式路由是(允许字符串/文件中没有带短标记的'php'。没有结尾?>(出于某种原因Zend建议这样做?),当然还有UNgreedy&DOTALL模式:

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

好吧,你可以使用DomDocument来做这件事

function stripPHPFromHTML($html) {
    $dom = new DomDocument();
    $dom->loadHtml($html);
    removeProcessingInstructions($dom);
    $simple = simplexml_import_dom($d->getElementsByTagName('body')->item(0));
    return $simple->children()->asXml();
}

function removeProcessingInstructions(DomNode &$node) {
    foreach ($node->childNodes as $child) {
        if ($child instanceof DOMProcessingInstruction) {
            $node->removeChild($child);
        } else {
            removeProcessingInstructions($child);
        }
    }
}
这两项职能将转变

$str = '<?php echo "foo"; ?><b>Bar</b>';
$clean = stripPHPFromHTML($str);
$html = '<b>Bar</b>';
$str='Bar';
$clean=stripPHPFromHTML($str);
$html='Bar';

编辑:事实上,在看了Wrikken的答案后,我意识到这两种方法都有缺点。。。我的需要某种程度上有效的HTML标记(Dom是不错的,但它不会解析
foo),一个简单的解决方案是使用php标记分解成数组,删除之间的任何内容,并内爆回字符串

function strip_php($str) {

  $newstr = '';

  //split on opening tag
  $parts = explode('<?',$str);

  if(!empty($parts)) {
      foreach($parts as $part) {

          //split on closing tag
          $partlings =  explode('?>',$part);
          if(!empty($partlings)) {

              //remove content before closing tag
              $partlings[0] = '';
          }

          //append to string
          $newstr .= implode('',$partlings);
      }
  }
  return $newstr;
}
function strip\u php($str){
$newstr='';
//打开标签时拆分
$parts=爆炸(“”,$part);
如果(!空($partings)){
//关闭标记前删除内容
$partlings[0]='';
}
//附加到字符串
$newstr.=内爆(“”,$partings);
}
}
返回$newstr;
}
这比正则表达式慢,但不需要有效的html或php;它只需要关闭所有php标记

对于不总是包含最终结束标记的文件和常规错误检查,如果缺少结束标记,您可以对标记进行计数并附加一个结束标记,或者在开始和结束标记未按预期相加时发出通知,例如,在函数开始处添加以下代码。但这会使其速度减慢一点:)

$tag_diff=(substr_count($str');
//如果少了一个结束标记,则追加
如果($tag_diff==1)$str.='?>';
//如果标记不正确,则分析错误
如果($tag_diff<0 | |$tag_diff>1)死亡('错误:标记不匹配。
(开始减去结束标记='.$tag_diff.)

倾销内容:


'.htmlentities($str));
这是@jon建议的strip_php的增强版,能够用另一个字符串替换代码的php部分:

/**
 * Remove PHP code part from a string.
 *
 * @param   string  $str            String to clean
 * @param   string  $replacewith    String to use as replacement
 * @return  string                  Result string without php code
 */
function dolStripPhpCode($str, $replacewith='')
{
    $newstr = '';

    //split on each opening tag
    $parts = explode('<?php',$str);
    if (!empty($parts))
    {
        $i=0;
        foreach($parts as $part)
        {
            if ($i == 0)    // The first part is never php code
            {
                $i++;
                $newstr .= $part;
                continue;
            }
            //split on closing tag
            $partlings = explode('?>', $part);
            if (!empty($partlings))
            {
                //remove content before closing tag
                if (count($partlings) > 1) $partlings[0] = '';
                //append to out string
                $newstr .= $replacewith.implode('',$partlings);
            }
        }
    }
    return $newstr;
}
/**
*从字符串中删除PHP代码部分。
*
*@param string$str要清理的字符串
*@param string$replacewith字符串用作替换
*@返回字符串不带php代码的结果字符串
*/
函数dolStrippCode($str,$replacewith='')
{
$newstr='';
//在每个开始标记上拆分
$parts=爆炸(“”,$part);
如果(!空($partings))
{
//关闭标记前删除内容
如果(计数($partings)>1)$partings[0]='';
//附加到输出字符串
$newstr.=$replacewith.introde(“”,$partings);
}
}
}
返回$newstr;
}

Pro提示:您不会涵盖与正则表达式进行括号匹配的所有情况。如果您知道只有一组标记,或者您有其他一些约束,则可以使用正则表达式。大括号匹配是一种非正则语言。:p您可以提供更多上下文吗?可能有一种方法可以实现您想要的内容,而不必这样做利用一个变量自存储php。很好的一点是,如果使用无效的php,我确实会失败。将其添加到答案中以获得良好的度量。只需注意,您可能无法从正则表达式解决方案中获得有效的HTML…
foo
将产生
;$bar='something';?>foo
。这种情况下,没有完美的解决方案……将每个解决方案组合起来以获得一个“最佳”…事实上,没有完美的解决方案。如果实际问题可以在更高的层次上得到解决,这样就不必使用我们的模糊逻辑,这将是更好的选择。当你需要一些准确的东西时,这个解决方案做得非常好。谢谢。
/**
 * Remove PHP code part from a string.
 *
 * @param   string  $str            String to clean
 * @param   string  $replacewith    String to use as replacement
 * @return  string                  Result string without php code
 */
function dolStripPhpCode($str, $replacewith='')
{
    $newstr = '';

    //split on each opening tag
    $parts = explode('<?php',$str);
    if (!empty($parts))
    {
        $i=0;
        foreach($parts as $part)
        {
            if ($i == 0)    // The first part is never php code
            {
                $i++;
                $newstr .= $part;
                continue;
            }
            //split on closing tag
            $partlings = explode('?>', $part);
            if (!empty($partlings))
            {
                //remove content before closing tag
                if (count($partlings) > 1) $partlings[0] = '';
                //append to out string
                $newstr .= $replacewith.implode('',$partlings);
            }
        }
    }
    return $newstr;
}