RegEx to match value of a variable or a string (with or without quotes)

前端 未结 2 577
南旧
南旧 2021-01-22 20:42

Here is my dilemma:

I wrote this RegEx pattern which works in my sandbox but does not work on my website:

Sandbox: http://regex101.com/r/vP3uG4

Pattern:<

相关标签:
2条回答
  • 2021-01-22 21:04

    If the variable $value contains a numerical value then the replacement pattern in your preg_replace will look like this: $12$3

    That's true but not as you expected. In Regex Engine, $ffffd or here $dd (which are equal to \ffffd and \dd) are treated as octal numbers.

    So in this case $12 means a octal index 12 which is equal to a kind of space in ASCII.

    In the case of working with these tricky issues in Regular Expressions you should wrap your backreference number within {} so it should be ${1}2${3}

    Change your replacement pattern to '${1}'.$value.'${3}'

    0 讨论(0)
  • 2021-01-22 21:13

    Okay, found out the issue. The solution is to wrap the backreference in ${}.

    Quoting the PHP manual:

    When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar \\1 notation for your backreference. \\11, for example, would confuse preg_replace() since it does not know whether you want the \\1 backreference followed by a literal 1, or the \\11 backreference followed by nothing. In this case the solution is to use \${1}1.

    So, your code should look like:

    header('Content-Type: text/plain');
    
    $variable = 'tbs_development';
    $value = '333';
    
    $savedsettings_temp = <<<'CODE'
    $tbs_underconstruction = 'foo';
    $tbs_development = 0;
    CODE;
    
    $pattern = '/(.*[$]'.preg_quote($variable).'\s*=\s*\'?)(.*?)(\'?;.*)/is';
    $replacement = '${1}'.$value.'${3}';
    
    $savedsettings_new = preg_replace($pattern, $replacement, $savedsettings_temp);
    
    echo $savedsettings_new;
    

    Output:

    $tbs_underconstruction = 'foo';
    $tbs_development = 333;
    

    Demo.

    0 讨论(0)
提交回复
热议问题