dongxing7083 2011-11-01 22:22
浏览 44
已采纳

使用preg_replace_callback()回调在PHP中访问全局状态

I've got a piece of text, for example:

XYZ id dui vel erat bibendum hendrerit aliquet ac lorem. Integer ABC turpis, facilisis sit amet ultricies non, tempor LMNOP est. Aliquam sit amet sapien justo. Quisque TUV dolor dolor, eu sodales mi.

I need to replace the bolded words with numbered placeholders.

%%%1%%% id dui vel erat bibendum hendrerit aliquet ac lorem. Integer %%%2%%% turpis, facilisis sit amet ultricies non, tempor %%%3%%% est. Aliquam sit amet sapien justo. Quisque %%%4%%% dolor dolor, eu sodales mi.

Doing this replacement, I need to store into an array the text it's replacing (e.g. XYZ) and keyed to the number of the placeholder (e.g. 1), such that I can go back and swap them back out with the original values later on.

The difficult part is that I don't know the replacement text in advance, so I need a callback to generate it based on the current count of items that have been replaced already.

I am running on an older version of PHP and do not have anonymous functions available in my toolkit, so I believe I am limited to callbacks using preg_replace_callback. It seems my problem boils down to the fact that I need the functions I create (using create_function) to be able to access some shared global state -- at the very least a shared global array where I can push and pop text that was replaced onto the stack.

Is this possible?

  • 写回答

3条回答 默认 最新

  • dtnpzghys01643322 2011-11-01 22:33
    关注

    Instead of using create_function() you will find it easier to make a regular function. (It's just easier not to have to deal with the complicated string escaping needed.)

    Use global $var; to set a global.

    Then after running your replace access that global (if the replace call is in a function you will need to say global $var; there as well).

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

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用