开发者

Replace some strings in PHP with regex?

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 the开发者_JS百科n 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?


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;


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜