【问题标题】:Replace some strings in PHP with regex?用正则表达式替换PHP中的一些字符串?
【发布时间】:2026-01-13 16:50:01
【问题描述】:

我需要为我在 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>

我真的不擅长正则表达式,有人可以帮我解决这个问题吗?

【问题讨论】:

  • 奇怪的类名是怎么回事?
  • @thephpdeveloper:一些 JS 插件使用这种奇怪的类来指定参数,尽管它们通常在相关类中的任何地方都不需要空格(即unrelatedclass brush:js; 而不是unrelatedclass brush: js;)。

标签: php regex


【解决方案1】:

要替换字符串中的字符串,您只需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;

【讨论】:

    【解决方案2】:
    $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 源文件)。

    【讨论】:

      最近更新 更多