2010-01-28 40 views
1

我需要做一個簡單的正則表達式查找並用PHP代替我的語法高亮腳本。用正則表達式替換PHP中的一些字符串?

我需要一個代碼字符串,它實際上是一個完整的php文件,讀入這樣的字符串。

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

,然後找到這些所有出現,並做了替換...

查找:[PHP]<pre class="brush: php;">
查找替換:[/ PHP]和替換與</pre>

找到[javascript],用<pre class="brush: js;">
查找替換:[/ JavaScript的]</pre>

代替我真的很不好用正則表達式可能有人請幫助我?

+0

什麼是奇怪的類名? – mauris 2010-01-28 05:20:12

+3

@thephpdeveloper:一些JS插件使用這些奇怪的類來指定參數,儘管它們在相關類中通常不需要任何空格(即「無關的類刷:js;」而不是「無關的類刷:js;」)。 – 2010-01-28 05:37:02

回答

4

要更換字符串內的字符串,您可以只需str_replace();。如果我沒有理解你的問題會是這個樣子:

$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; 
+0

完美,謝謝 – 2010-01-28 05:56:04

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 
); 

將取代打開和關閉標籤內的任何PHP源(短期和長期),將腳本標籤內更換任何JS源至少一個字符(將避免鏈接到JavaScript源文件的腳本標記)。