note 77317 modified in function.preg-replace by danbrown
| From: | danbrown@php.net | Date: | Fri, 28 Nov 2008 19:51:54 +0000 |
| Subject: | note 77317 modified in function.preg-replace by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-147149@lists.php.net to get a copy of this message | ||
From what I can see, the problem is, that if you go straight and substitute all 'A's wit
'T's you can't tell for sure which 'T's to substitute with 'A's
afterwards. This can be for instance solved by simply replacing all 'A's by another
character (for instance '_' or whatever you like), then replacing all 'T's by
'A's, and then replacing all '_'s (or whatever character you chose) by
'A's:
<?php
$dna = "AGTCTGCCCTAG";
echo
str_replace(array("A","G","C","T","_","-"),
array("_","-","G","A","T","C"), $dna);
//output will be TCAGACGGGATC
?>
Although I don't know how transliteration in perl works (though I remember that is kind of
similar to the UNIX command "tr") I would suggest following function for
"switching" single chars:
<?php
function switch_chars($subject,$switch_table,$unused_char="_") {
foreach ( $switch_table as $_1 => $_2 ) {
$subject = str_replace($_1,$unused_char,$subject);
$subject = str_replace($_2,$_1,$subject);
$subject = str_replace($unused_char,$_2,$subject);
}
return $subject;
}
echo switch_chars("AGTCTGCCCTAG",
array("A"=>"T","G"=>"C")); //output will be
TCAGACGGGATC
?>
--was--
From what I can see, the problem is, that if you go straight and substitute all 'A's wit
'T's you can't tell for sure which 'T's to substitute with 'A's
afterwards. This can be for instance solved by simply replacing all 'A's by another
character (for instance '_' or whatever you like), then replacing all 'T's by
'A's, and then replacing all '_'s (or whatever character you chose) by
'A's:
$dna = "AGTCTGCCCTAG";
echo
str_replace(array("A","G","C","T","_","-"),
array("_","-","G","A","T","C"), $dna);
//output will be TCAGACGGGATC
Although I don't know how transliteration in perl works (though I remember that is kind of
similar to the UNIX command "tr") I would suggest following function for
"switching" single chars:
function switch_chars($subject,$switch_table,$unused_char="_") {
foreach ( $switch_table as $_1 => $_2 ) {
$subject = str_replace($_1,$unused_char,$subject);
$subject = str_replace($_2,$_1,$subject);
$subject = str_replace($unused_char,$_2,$subject);
}
return $subject;
}
echo switch_chars("AGTCTGCCCTAG",
array("A"=>"T","G"=>"C")); //output will be
TCAGACGGGATC
http://php.net/manual/en/function.preg-replace.php