Search code examples
phpregexpreg-replacereplacepreg-replace-callback

RegEx: How to extract a value/number from a pattern and replace it with something else?


For instance I have this piece of data:

array(
    1 => 'Metallica',
    2 => 'Megadeth',
    3 => 'Anthrax',
    4 => 'Slayer',
    5 => 'Black Sabbath',
);

And I have this piece of text:

My first favorite band is: #band{2}, and after that it's: #band1. My over-all first metal band was: #band{5}, and I sometimes enjoy headbaning while listening to: #band3 or #band{4}.

So after the RegEx, it should look like this:

My first favorite band is: Megadeth, and after that it's: Metallica. My over-all first metal band was: Black Sabbath, and I sometimes enjoy headbaning while listening to: Anthrax or Slayer.

So, I need a pattern/example how can I extract numbers from these two patterns:

#band{NUMERIC-ID} or #bandNUMERIC-ID


Solution

  • No need for regular expressions, just use str_replace():

    $map = array();
    foreach ($bands as $k => $v){
        $map["#band".$k] = $v;
        $map["#band{".$k."}"] = $v;
    }
    
    $out = str_replace(array_keys($map), $map, $text);
    

    A demo: http://codepad.org/uPqGXGg6

    If you want to use regular expressions:

    $out = preg_replace_callback('!\#band((\d+)|(\{(\d+)\}))?!', 'replace_band', $text);
    
    function replace_band($m){
        $band = $GLOBALS['bands'][$m[2].$m[4]];
        return $band ? $band : 'UNKNOWN BAND';
    }
    

    A demo: http://codepad.org/2hNEqiCk

    [edit] updated for multiple forms of the token to replace