preg_replace_callback()
おそらくこれを行う最も簡単な方法です。1 回の操作で行う必要があります。このようなもの:
<?php
$string = "Dm F Bb F Am";
$replacements = array (
'Dm' => 'F#m',
'F' => 'A',
'Bb' => 'D',
'Am' => 'C#m',
'Bbm' => 'Dm',
'A' => 'C#',
'C' => 'E'
);
$New_string = preg_replace_callback('/\b('.implode('|', array_map('preg_quote', array_keys($replacements), array_fill(0, count($replacements), '/'))).')\b/', function($match) use($replacements) {
return $replacements[$match[1]];
}, $string);
echo $New_string;
動いているのを見る
さて、上記のコードが少しわかりにくいことはわかっているので、少し分解して、個々のコンポーネントが何をするかを見てみましょう。
// The input string and a map of search => replace
$string = "Dm F Bb F Am";
$replacements = array (
'Dm' => 'F#m',
'F' => 'A',
'Bb' => 'D',
'Am' => 'C#m',
'Bbm' => 'Dm',
'A' => 'C#',
'C' => 'E'
);
// Get a list of the search strings only
$searches = array_keys($replacements);
// Fill an array with / characters to the same length as the number of search
// strings. This is required for preg_quote() to work properly
$delims = array_fill(0, count($searches), '/');
// Apply preg_quote() to each search string so it is safe to use in the regex
$quotedSearches = array_map('preg_quote', $searches, $delims);
// Build the regex
$expr = '/\b('.implode('|', $quotedSearches).')\b/';
// Define a callback that will translate search matches to replacements
$callback = function($match) use($replacements) {
return $replacements[$match[1]];
};
// Do the replacement
$New_string = preg_replace_callback($expr, $callback, $string);