如何在php中用另一个数组字符串替换字符串

时间:2012-11-21 18:41:31

标签: php

实际上我想转换我在输入文本中输入的字符串,然后与另一个数组进行比较..请参阅下面的方案:

首先,我在输入文本中输入这种类型的字符串:acgta 其次,我想将“acgta”替换为a=T, c=G, g=C

的“TGCAT”

这是代码:

$data = "acgta";
$s = str_split($data);

$d = array("a" => "T","g" => "C","c" => "G","t" => "A");

foreach($d as $key1 => $value1) {
        echo str_replace($key1,$value1,$data);}

4 个答案:

答案 0 :(得分:4)

$data = "acgta";
echo str_replace(array('a', 'c', 'g', 't'), array('T', 'G', 'C', 'A'), $data);

$data = "acgta";
echo strtr($data, 'acgt', 'TGCA');

查看PHP手册页:

答案 1 :(得分:1)

您想使用strtr功能。如果您阅读PHP文档:http://www.php.net/manual/en/function.strtr.php

,这是非常明显的
$data = "acgta";
$d = array("a" => "T","g" => "C","c" => "G","t" => "A");

echo strtr($data, $d);

答案 2 :(得分:0)

str_replace与数组元素一起使用会更容易。见下文:

$data = "acgta";
$fromArr = array('a', 'g', 'c', 't');
$toArr = array('T', 'C', 'G', 'A');

echo str_replace($fromArr, $toArr, $data);

答案 3 :(得分:0)

你可以简单地使用它:

$string = "acgta";
$from = array('a', 'g', 'c', 't');
$to = array('T', 'C', 'G', 'A');
$string = str_replace($from, $to, $string);

或者以一种简单的方式:

$string = "acgta";
$string = str_replace(array('a', 'g', 'c', 't'), array('T', 'C', 'G', 'A'), $string);