0

我在preg_replace()使用数组时遇到问题。

基本上,我想转置这个字符串;

$string = "Dm F Bb F Am";

$New_string = "F#m D D A C#m";

这是我所做的:

$Find = Array("/Dm/", "/F/", "/Bb/", "/Am/", "/Bbm/", "/A/", "/C/");
$Replace = Array('F#m', 'A', 'D', 'C#m', 'Dm', 'C#', 'E');
$New_string = preg_replace($Find, $Replace, $string);

但我得到了这个结果:

E##m E# DE# E#m

问题是每个匹配都被以下内容替换,会发生这样的事情(例如 E##m):

Dm -> F#m -> A#m -> C##m -> E##m

是否有任何解决方案可以简单地将“Dm”更改为“F#m”,将“F”更改为“A”等?

谢谢 !

4

2 回答 2

4

您可以使用strtr()

<?php
    $string = "Dm F Bb F Am";
    $Find = Array('Dm', 'F', 'Bb', 'Am', 'Bbm', 'A', 'C');
    $Replace = Array('F#m', 'A', 'D', 'C#m', 'Dm', 'C#', 'E');

    $New_string = strtr($string, array_combine($Find, $Replace));

    echo $New_string;

    // F#m A D A C#m
于 2012-09-12T10:39:42.043 回答
1

preg_replace_callback()可能是最简单的方法,您需要在一次操作中完成。像这样的东西:

<?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);
于 2012-09-12T10:40:10.947 回答