[PHPTAL] <pre> element parsing - maybe someone will find this useful

Mynthon mynthon1 at gmail.com
Wed May 16 13:08:42 CEST 2007


On my website i have a lot of source code samples, and i'm using pre
elements for display. Because IE doesnt support new lines in pre
element i have to change all new lines to br and strip all new lines
so code:
<pre>
this
is
sample
</pre>

should look like this:
<pre>this<br />is<br />sample<br /></pre>

But i also need to convert all html special chars to entities.

So i wrote this (uses phptal pre filter -> look to manual):

class PREElements implements PHPTAL_Filter {
 public function filter($source){
 $PRE = array();

 preg_match_all('/\<pre\>\<\!\[CDATA\[(.*?)\]\]\>\<\/pre\>/s',
$source, $regs, PREG_SET_ORDER);

 $i=0;
 foreach($regs as $v){
  $v[1]=htmlspecialchars(trim($v[1]));
  $v[1]=str_replace("\r\n", "\n",$v[1]);
  $v[1]=str_replace("\r", "\n",$v[1]);
  $v[1]=str_replace("\n", "<br />",$v[1]);

  $PRE[$i]=$v[1];

  $source = str_replace($v[0], '<pre tal:content="structure
PRE/'.$i.'"></pre>', $source);

  $i++;
 }
 global $template;
 $template->PRE = $PRE;
 return $source;
 }
}

it will assign content from pre element (with <![CDATA[ ]]> section)
to array $template->pre (where $template is my template obj) and will
change all <pre /> elements to <pre tal:content="structure PRE/index"
/>.

so something like this

<pre><![CDATA[
<script type="text/javascript">
       if(a<b && b>c){
               alert('<br />');
       }
</script>
]]></pre>

will be converted to

<pre>&lt;script type=&quot;text/javascript&quot;&gt;<br />      if(a&lt;b
&amp;&amp; b&gt;c){<br />               alert('&lt;br /&gt;');<br />    }<br
/>&lt;/script&gt;</pre>

-- 
mynthon
http://www.mynthon.net



More information about the PHPTAL mailing list