tags:

views:

55

answers:

2

I need to do a simple regex find and replace with PHP for my syntax highlighting script in PHP.

I need to take a string of code which will actually be a whole php file that is read into a string like this.

$code_string = 'the whole source code of a php file will be held in this string';

And then find all occurences of these and do a replace...

Find: [php] and replace with <pre class="brush: php;">
Find: [/php] and replace with </pre>

Find [javascript] and replace with <pre class="brush: js;">
Find: [/javascript] and replace with </pre>

I really am not good with regex could someone please help me with this?

+2  A: 

For the replacement of strings within strings you can just str_replace();. If I understand your question correctly it would look something like this:

$code_string = htmlentities(file_get_contents("file.php"));
$old = array("[php]","[javascript]","[/php]","[/javascript]");
$new = array('<pre class="brush: php;">','<pre class="brush: js;">','</pre>','</pre>');
$new_code_string = str_replace($old,$new,$code_string);
echo $new_code_string;
Sam152
perfect, thanks
Jack Ferrari
A: 
$out = preg_replace(
  array(
   '/\<\?(php)?(.*)\?\>/s',
   '/\<script(.*) type\=\"text\/javascript\"(.*)\>(.+)\<\/script\>/s'
  ),
  array(
   '<pre class="brush: php;">$2</pre>',
   '<pre class="brush: js;">$3</pre>'
  ),
  $code
 );

Will replace any PHP source within open and close tags (short and long), will replace any JS source within script tags with at least one character (will avoid script tags linked to javascript source files).

rob