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 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错