1

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

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

这是代码:

$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

4 回答 4

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 手册页:

于 2012-11-21T18:45:05.903 回答
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);
于 2012-11-21T18:45:11.510 回答
0

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

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

echo str_replace($fromArr, $toArr, $data);
于 2012-11-21T18:45:17.117 回答
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);
于 2012-11-21T18:46:31.973 回答