1

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
  • what's with the weird class names? Commented Jan 28, 2010 at 5:20
  • 3
    @thephpdeveloper: some JS plugins use such weird classes to specify parameters, though they usually require no spaces anywhere in the relevant class (i.e. unrelatedclass brush:js; rather than unrelatedclass brush: js;). Commented Jan 28, 2010 at 5:37

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

Comments

0
$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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.