PHP Regular replaces the first bit with 0. is ignored

Source: Internet
Author: User
$subject = '0300020F005176C5A11A730004F955A2A20CD8-367C-EC5B-9D8C-2CAA0B8FE45D';echo preg_replace('/^(\w{8})\w{2}/i','$1'.'08',$subject);// 输出结果:85176C5A11A730004F955A2A20CD8-367C-EC5B-9D8C-2CAA0B8FE45D// 期望结果:0300020F085176C5A11A730004F955A2A20CD8-367C-EC5B-9D8C-2CAA0B8FE45D// 但是:preg_replace('regex','$1'.'__',$subject);  这样是没有问题的

Reply content:

$subject = '0300020F005176C5A11A730004F955A2A20CD8-367C-EC5B-9D8C-2CAA0B8FE45D';echo preg_replace('/^(\w{8})\w{2}/i','$1'.'08',$subject);// 输出结果:85176C5A11A730004F955A2A20CD8-367C-EC5B-9D8C-2CAA0B8FE45D// 期望结果:0300020F085176C5A11A730004F955A2A20CD8-367C-EC5B-9D8C-2CAA0B8FE45D// 但是:preg_replace('regex','$1'.'__',$subject);  这样是没有问题的

Quote from PHP manual preg_replace function to a back-reference description: Preg_replace

When working in replacement mode and the back reference is followed by a second number (for example, adding a text number immediately after a matching pattern), you cannot use syntax such as \1 to describe the back reference. For example, \11 will make preg_replace () do not understand what you want is a \1 back to the reference followed by a text 1, or a \11 after the reference is not followed by anything. In this case the solution is to use \${1}1. This creates a separate, forward-referencing, 1-independent source.

Your replacement part is "$108", so you need to replace it with ${1} to avoid confusion.


  
   

echo preg_replace_callback('/^(\w{8})(\w{2})/i',create_function(        // single quotes are essential here,        // or alternative escape all $ as \$        '$matches',        'return $matches[1].\'08\';'    ),$subject);

这样,callback处理

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.