3 回答
Why not KISS (Keep It Simple, Stupid):
echo str_replace(
array('<pre>', '</pre>'),
array('<code>', '</code>'),
$your_html_with_pre_tags
);
Look at the manual. Changing <pre>
tags to <code>
should be as simple as:
$str = '<pre lang="php">
echo "test";
</pre>
<pre lang="html4strict">
<div id="test">Hello</div>
</pre>';
require_once("simplehtmldom/simple_html_dom.php");
$html = str_get_html($str);
foreach($html->find("pre") as $pre) {
$pre->tag = "code";
$pre->lang = null; // remove lang attribute?
}
echo $html->outertext;
// <code>
// echo "test";
// </code>
// <code>
// <div id="test">Hello</div>
// </code>
PS: you should encode the "
, <
and >
characters in your input.
Just replacing pre
tags with code
tags changes the meaning and the rendering essentially and makes the markup invalid, if there are any block-level elements like div
inside the element. So you need to revise your goal. Check out whether you can actually keep using pre
. If not, use <div class=pre>
instead, together with a style sheet that makes it behave like pre
in rendering. When you just replace pre
tags with div
tags, you won’t create syntax errors (the content model of div
allows anything that pre
allows, and more).
Regarding the lang
attribute, lang="php"
is incorrect (by HTML specs, lang
attribute specifies the human language of the content, using standard language codes), but the idea of coding information about computer language is good. It may help styling and scripting later. HTML5 drafts mention that such information can be coded using a class name that starts with language-
, e.g. class="language-php"' (or, when combined with another class name,
class="language-php pre"'.