dongxian3574 2013-04-19 21:04
浏览 28
已采纳

取[code] [/ code]之间的内容并应用更改

I want to make code box, where I can apply changes. If I have this: $var= "word"; inside these [code] HERE [/code], I will change $var into red color and "word" into green.

I used preg_replace to select what's between these [code] [/code].

$codebox = preg_replace("/\[code\](.*?)\[\/code\]/","$1",$string);

the thing is with preg_replace I can do outsider changes (to whole code). I want to do changes to what inside these [code] [/code]. Like: background color, all text color, all text font, all text font-weight and etc... that's mean I need to get it out apply changes then put it back.

I want to be able to use str_replace and preg_replace functions on $1 not on $string.

for example to change"word" into green. I'll use

preg_replace("/(\".*?\")/","<span style='color: #090;'>$1</span>",$string)

and I can't use preg_replace inside preg_replace, can I? I don't know if I'm using the wrong function here, or there is a way do this.

you may find my patterns wrong, correct me I just learnt them yesterday.

  • 写回答

2条回答 默认 最新

  • doubeng9567 2013-04-19 21:29
    关注

    Using preg_replace_callback:

    $string = '[code]$var = "word";[/code]';
    $codebox = preg_replace_callback("/\[code\](.*?)\[\/code\]/",function($m){
        // The following replacements are just a demo
        $m[1] = preg_replace('/"([^"]+)"/', '"<span style="color:#0D0;">$1</span>"', $m[1]); // green value
        $m[1] = preg_replace('/(\$\w+)/', '<span style="color:#F00;">$1</span>', $m[1]); // Red var name
        $m[1] = str_replace(' = ', '<span style="color:#00F;"> = </span>', $m[1]); // blue = sign
        return $m[1];
    },$string);
    echo $codebox;
    

    Online demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加