dousui3124 2015-02-06 15:55
浏览 47

不推荐使用preg_replace():不推荐使用/ e修饰符,而是使用preg_replace_callback

Apologies for asking this question again. I have seen some of the other answers to this question but to be frank I'm so bad at regexing I couldn't figure out how to exactly use those solutions to fix my own problem

Here is my code that I'm having trouble with.

$features = preg_replace('!s:(\d+):"(.*?)";!es', "'s:'.strlen('$2').':\"$2\";'", $features);
  • 写回答

1条回答 默认 最新

  • doq13207 2015-02-06 16:02
    关注
    $features = preg_replace_callback('!s:(\d+):"(.*?)";!s', function($c) {
        return serialize($c[2]);
    }, $features);
    

    When-/Where-ever the pattern matches in the source ($features in the example) the callback is invoked and all captures are passed as an array ($c in the example).
    $c[0] is the complete match, $c[1] the first sub-capture (the string that maches \d+), $c[2] the seconds sub-capture (the string that matches .*?).
    The complete match is replaced by whatever the callback returns.
    Take a look at this example:

    <?php
    echo "
    
    -------- example #1 --------
    ";
    $src = '1a2b3c';
    $result = preg_replace_callback('!\d!', function($c) {
        cprint($c);
        $retval = $c[0]+22;
        echo '  cb returns: ', $retval, "
    ";
        return $retval;
    }, $src);
    echo 'result: ', $result, "
    ";
    
    
    echo "
    
    -------- example #2 --------
    ";
    $src = '1a2b3c4a5b6';
    $result = preg_replace_callback('!(\d)a(\d)!', function($c) {
        cprint($c);
    
        $retval = sprintf('%dA%d', $c[1]+22, $c[2]+33);
        echo '  cb returns: ', $retval, "
    ";
        return $retval;
    }, $src);
    echo 'result: ', $result, "
    ";
    
    
    
    function cprint(array $c) {
        echo 'callback invoked
      $c=', preg_replace('!\s+!', ' ', var_export($c, true)), "
    ";
    }
    

    prints

    -------- example #1 --------
    callback invoked
      $c=array ( 0 => '1', )
      cb returns: 23
    callback invoked
      $c=array ( 0 => '2', )
      cb returns: 24
    callback invoked
      $c=array ( 0 => '3', )
      cb returns: 25
    result: 23a24b25c
    
    
    -------- example #2 --------
    callback invoked
      $c=array ( 0 => '1a2', 1 => '1', 2 => '2', )
      cb returns: 23A35
    callback invoked
      $c=array ( 0 => '4a5', 1 => '4', 2 => '5', )
      cb returns: 26A38
    result: 23A35b3c26A38b6
    
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向