正则表达式:如何从模式中提取值/数字并将其替换为其他内容


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

例如,我有以下数据:

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

我有这段文字:

我最喜欢的第一个乐队是:#band{2},之后是:#band1。我 总的来说,第一个金属乐队是:#band{5},我有时喜欢 边听边头:#band3#band{4}

所以在正则表达式之后,它应该看起来像这样:

我最喜欢的乐队是:Megadeth,之后是:Metallica。 我的第一个金属乐队是:黑色安息日,我有时喜欢 边听边头:炭疽或杀手

因此,我需要一个模式/示例,如何从这两种模式中提取数字:

#band{数字 ID}#bandNUMERIC-ID

不需要正则表达式,只需使用 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);

演示:http://codepad.org/uPqGXGg6

如果要使用正则表达式:

$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';
}

演示:http://codepad.org/2hNEqiCk

[编辑] 更新了多种形式的令牌以替换

尝试这样的事情

$txt = 'your text with bands';
foreach($arr as $key=>$val){
    $txt = preg_replace('/#band'.$key.'([^0-9])/', $val.'$1', $txt);
    $txt = preg_replace('/#band{'.$key.'}/', $val.'$1', $txt);
}
//detect the error
if(preg_match('/#band[^0-9]+/', $txt) || preg_match('/#band{[^0-9]+}/', $txt){
  //error!!!
}
//replace the non found bands with a string
$txt = preg_replace('/#band[^0-9]+/', 'failsafe', $txt);
$txt = preg_replace('/#band{[^0-9]+}/', 'failsafe', $txt);