用正则表达式替换PHP中的一些字符串? [英] Replace some strings in PHP with regex?

查看:93
本文介绍了用正则表达式替换PHP中的一些字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要做一个简单的正则表达式查找,并用PHP替换我的PHP语法突出显示脚本.

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

我需要采用一串代码,实际上这将是一个完整的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...

查找: [php] 并替换为 <pre class="brush: php;">
查找: [/php] 并替换为 </pre>

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

找到 [javascript] 并替换为 <pre class="brush: js;">
查找: [/javascript] 并替换为 </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?

推荐答案

要替换字符串中的字符串,您只需str_replace();.如果我正确理解了您的问题,它将看起来像这样:

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;

这篇关于用正则表达式替换PHP中的一些字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆