bleedr
bleedr

Reputation: 25

Replace letters using array and preg_replace in PHP

I have the following code:

        $qSeq        = "ATTA";
        $suchmuster  = array("/A/","/T/","/G/","/C/","/U/");
        $ersetzungen = array("T","A","C","G","A");
        $qSeq        = preg_replace($suchmuster, $ersetzungen, $qSeq);
        echo $qSeq;

My aim is that i.e. ATTA becomes TAAT, this logic works fine in Ruby, but PHP will kinda produce AAAA. Any idea how this might work with PHP ?

Tnx!

Upvotes: 1

Views: 64

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

If your replace may entail changing letters that you've already changed, then use strtr()

$qSeq = 'CATGUT';
$suchmuster  = array("A","T","G","C","U");
$ersetzungen = array("T","A","C","G","A");
$qSeq        = strtr($qSeq, array_combine($suchmuster, $ersetzungen));
echo $qSeq;

gives

GTACAA

Upvotes: 1

Related Questions