用正则表达式替换PHP中的一些字符串?
问题描述:
我需要做一个简单的正则表达式查找并用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>
代替我真的很不好用正则表达式可能有人请帮助我?
答
要更换字符串内的字符串,您可以只需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
答
$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源文件的脚本标记)。
什么是奇怪的类名? – mauris 2010-01-28 05:20:12
@thephpdeveloper:一些JS插件使用这些奇怪的类来指定参数,尽管它们在相关类中通常不需要任何空格(即“无关的类刷:js;”而不是“无关的类刷:js;”)。 – 2010-01-28 05:37:02