【发布时间】:2016-10-31 06:49:22
【问题描述】:
我在下面有这段代码,它在用户问题中找到小于和大于 HTML 字符实体,并用合适的实体名称替换它们
$string = $this->input->post('question');
$find_and_replace = array(
'<' => '<',
'>' => '>',
);
$new_data = str_replace(array_keys($find_and_replace), array_values($find_and_replace), $string);
当问题中有&lt;pre&gt;&lt;/pre&gt;和&lt;code&gt;&lt;/code&gt;之类的标签时
它也替换了它们 &lt;pre&gt;&lt;/pre&gt; 和 &lt;code&gt;&lt;/code&gt;
我不希望这种情况发生只是为了替换标签内的内容。
问题我怎样才能仍然使用 str_replace 但只能使用内容 在 pre 标签或 code 标签内。
public function preview() {
$data = array('success' => false, 'question' => '', 'tag' => '');
if ($_POST) {
$string = $this->input->post('question');
$find_and_replace = array(
'<' => '<',
'>' => '>',
);
$new_data = str_replace(array_keys($find_and_replace), array_values($find_and_replace), $string);
$data['question'] = $new_data;
$data['success'] = true;
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}
function get_everything_in_tags($string, $tagname)
{
$pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
preg_match($pattern, $string, $matches);
return $matches[1];
}
【问题讨论】:
-
我不想删除前置标签,我只是希望它避免在前置标签周围替换
<和>。
标签: php codeigniter