Help - Search - Members - Calendar
Full Version: PHP Function
Weborum Webmaster Forum > Web Page Design > PHP
Joe
I have a small function which is suprisingly difficult ... I'm not too good with my regex so I was hoping someone would be able to give me a hand with it.

Basically, when outputting certain data, there will be HTML tags that I need changing using preg_replace. There is only one tag, but it may have a class applied to it.

CODE
<pre>

<pre class="red">

<pre class="blue">


Those are the only occurances of PRE that will need to be changed. They need to be changed to;

CODE
<div class="code">

<div class="code red">

<div class="code blue">


Which is fair enough ... easily done. But now the tricky part I'm having problems with is applying nl2br() to the code which only appears within those PRE tags.

My current function makes all the tag changes;

PHP
<?php
function ConvertPRE($string) {
   
$pre = array('<pre>', '</pre>', '<pre class="');
   
$div = array('<div class="code">', '</div>', '<div class="code ');
   return
str_replace($pre, $div, $string);
}
?>


Does anyone have any idea how I can do this?
sjthomas
I've got to be honest mate, I havn't looked at any code for a while. off the top of my head I'd say you need to follow the same principal as the XHTML compliant highlighting stuff that you posted about a while back ( http://forum.weborum.com/index.php?showtopic=3043 ). Personally I would go down that route and use concatenation to chuck a function in amongst the preg_replace statement and deal with the normal pre tag with one set of statements and the pre tags with a class in another (because I'm lazy wink.gif )

PHP
<?php
$match
= array('#\[pre\](.*?)\[\/pre\]#se');
$replace = array("'<div class=\"code&#092;">'.nl2br($1).'</div>'");
$string = preg_replace($match, $replace, $string);?>



The above is an edited bit from that post. God knows if it'll work. Its supposed to handle the normal pre tags, the regexp would need to be edited a bit to work with the pre tags that have classes. let me know if it works out, if not I'll fire up apache on my machine (after wiping the dust off...) and have a gander...
Joe
Yeah, I considered making separate functions for each class ... but I still can't make the default <pre> tag change work yet haha.

I've tried loads of variations but with no success.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2008 Invision Power Services, Inc.