简体   繁体   中英

Regular Expression Replace a group: varying the output depending upon what it matches

Regular Expression Replace a group: varying the output depending upon what it matches

While using PHP Live Regex - A live Regular Expression Tester for PHP

I am unable to get the final group to replace with variable output depending upon what expression is encountered. I am unsure of how to format the last replacement group so that it does not output the literal value.

I want to do something like this:

Regular Expression:
('group1',) (group2,) (group3,) (alpha|beta|charlie)

Replace with:
$1 $2 $3 (1|2|3)

And was hoping for a result like this:

Example 1:
Source: 'group1', group2, group3, alpha
Result: 'group1', group2, group3, 1

Example 2:
Source: 'group1', group2, group3, beta
Result: 'group1', group2, group3, 2

etc.

But, instead I get this:

Example 1:
Source: 'group1', group2, group3, alpha
Result: 'group1', group2, group3, (1|2|3)

Example 2:
Source: 'group1', group2, group3, beta
Result: 'group1', group2, group3, (1|2|3)

Thanks in advance for help to this issue.

Mike

PCRE engine does not support conditional replacement patterns. In PHP, you just need to use preg_replace_callback and replace the 4th group with the right value based on the $matches[4] ( $m[4] is used below) value.

See a PHP demo :

$string = "'group1', group2, group3, alpha 'group1', group2, group3, beta";
$pattern = "/('group1',) (group2,) (group3,) (alpha|beta|charlie)/i";
$data = array("alpha" => "1", "beta" => "2", "charlie" => "3");
$inc = 0;

echo preg_replace_callback($pattern, function ($m) use ($data) {
        return  $m[1] . " " . $m[2] . " " . $m[3] . " " . $data[$m[4]];
    }, $string);

Output: 'group1', group2, group3, 1 'group1', group2, group3, 2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM