drl37530 2013-09-25 06:11
浏览 67
已采纳

preg_replace_callback正则表达式问题,与(。*?)匹配返回数组

Given the string {{esc}}"Content"{{/esc}} ... {{esc}}"More content"{{/esc}} I would like to output \"Content\" ... \"More content\" e.g., I am trying to escape the quotes inside a string. (This is a contrived example, though, so an answer with something like 'just use this library to do it' would be unhelpful.)

Here is my current solution:

return preg_replace_callback(
  '/{{esc}}(.*?){{\/esc}}/', 
  function($m) {
    return str_replace('"', '\\"', $m[1]);
  },
  $text
);

As you can see, I need to say $m[1], because a print_r reveals that $m looks like this:

Array 
(
    [0] => {{esc}}"Content"{{/esc}}
    [1] => "Content"
)

or, for the second match,

Array 
(
    [0] => {{esc}}"More content"{{/esc}}
    [1] => "More content"
)

My question is: why does my regex cause $m to be an array? Is there any way I can get the result of $m[1] as just a single variable $m?

  • 写回答

2条回答 默认 最新

  • dpw5865 2013-09-25 06:34
    关注

    With the help of Jack, I answered my own question here since srain did not make this point clear: The second element of the array is the result captured by the parenthesized subexpression (.*?), per the PHP manual. Indeed, there does not appear to be a convenient way to extract the string matched by this subexpression otherwise.

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

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测