[英]Preg_replace not replacing correctly
我在我的项目上工作,人们可以在我的数据库中添加PHP代码片段。 使用SyntaxHighlighter显示这些im。 我使用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();
}
尝试
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);
}
谢谢大家的答案。 我通过在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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.