本文介绍了有两个数组的preg_replace的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've have a problem with preg_replace() using arrays.

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

Basically, I'd like to transpose this string ;

$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);

但是我得到的结果却是:

But I get this result instead :

E ## m E#DE#E#m

E##m E# D E# E#m

问题是每个匹配项都被以下内容代替,类似的情况发生(例如E ## m):

Problem is that every match is replaced by the following, something like this happens (example for E##m):

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

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

是有什么解决方案可以简单地将'Dm'更改为'F#m',将 F更改为 A,等等?

Is there any solution to simply change 'Dm' to 'F#m', "F" to "A", etc ?

谢谢!

推荐答案

您可以使用:

<?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

这篇关于有两个数组的preg_replace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 19:13