Preg_replace无法正确替换

时间:2012-10-15 17:12:07

标签: php mysql preg-replace

我正在开发一个我的项目,人们可以在我的数据库中添加PHP代码。 使用SyntaxHighlighter显示这些im。我使用preg_replace来逃避所有<预标签内的括号。这是必需的,因此syntaxhighlighter正确地呈现代码。它在php标签和东西上运行良好..

这是我从我的数据库中呈现输入的代码:

 public function renderPre($input) // Function to escape html brackets within PRE tags. 
{
    $temp = preg_replace('/<pre>(.*?)<\/pre>/ise', "'<pre>' . htmlspecialchars('$1') . '</pre>'", $input);  
    return str_replace('<pre>', '<pre class=\'brush: php\'>', $temp);
} 

一旦括号被转义,我就在pre标签中添加一个类来激活荧光笔。

在我的数据库中,代码存储如下:

<pre><?php
foreach ($tutorial as $row)
{
    echo "<h1>".$row['title']."</h1>";
    echo $this->content_model->renderPre($row['intro']);
    echo $this->content_model->renderPre($row['body']);
}
?></pre>

现在在我的实际页面上,从数据库中检索代码并在荧光笔中显示,这是输出:

<?php
foreach ($tutorial as $row)
{
    echo \"<h1>\".$row['title'].\"</h1>\";
    echo $this->content_model->renderPre($row['intro']);
    echo $this->content_model->renderPre($row['body']);
}
?>

在H1标签所在的行,它会添加一些额外的斜杠(\) 我不知道为什么会这样做。它必须与渲染函数中的/ ise有关。

有没有人知道如何解决这个问题?

谢谢!

编辑:

从数据库中检索内容的代码:

    public function get_tutorial()
    {
        $sql = "Select
  tutorial.*,
  category.name,
  category.slug As slug1
From
  tutorial Inner Join
  category On tutorial.category_id = category.id
  WHERE tutorial.slug = '".$this->uri->segment(3)."'
  ";

  $query = $this->db->query($sql);
  return $query->result_array();
    }

2 个答案:

答案 0 :(得分:0)

尝试

public function renderPre($input) // Function to escape html brackets within PRE tags. 
{
    $input = htmlspecialchars_decode($input);
    $temp = preg_replace('/<pre>(.*?)<\/pre>/ise', "'<pre>' . htmlspecialchars('$1') . '</pre>'", $input);  
    return str_replace('<pre>', '<pre class=\'brush: php\'>', $temp);
}

答案 1 :(得分:0)

谢谢大家的答案。我通过在renderpre函数中添加stripslashes来使它正常工作:

 public function renderPre($input) // Function to escape html brackets within PRE tags. 
{
    $temp = preg_replace('/<pre>(.*?)<\/pre>/ise', "'<pre>' . htmlspecialchars('$1') . '</pre>'", $input);  
    return str_replace('<pre>', '<pre class=\'brush: php\'>', stripslashes($temp));
}