4

我正在处理我的一个项目,人们可以将一些 php 代码添加到我的数据库中。使用 SyntaxHighlighter 显示这些即时消息。我使用 preg_replace 来转义 pre 标记中的所有 < 括号。这是必需的,因此 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();
    }
4

2 回答 2

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);
}
于 2012-10-15T19:31:12.210 回答
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));
} 
于 2012-10-15T20:26:11.810 回答