字符串 替换

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-23 13:54:50804browse

1要替换成apple,2要替换成pear,3要换成banana,4要换成orange。

这样的话,从数据库里读出来是23  。结果是pearbanana。
1234 ===applepearbananaorange。

就是要写一个这样的函数,根据数据查出来的数据换成水果名。

简洁的函数最好,不胜感激


回复讨论(解决方案)

不需要写,php 已经提供了

$d = array( 1 => 'apple', 2 => 'pear', 3 => 'banana', 4 => 'orange');echo strtr('1234',$d);
applepearbananaorange

科学家就是科学家,哎。老徐教教我们该如何学习php吧。

不需要写,php 已经提供了

$d = array( 1 => 'apple', 2 => 'pear', 3 => 'banana', 4 => 'orange');echo strtr('1234',$d);
applepearbananaorange

$a = array(1,2,3,4);$b   = array('apple','pear','banana','orange');$output  = str_replace($a, $b, '1234');echo $output;

$str = '1234';echo change($str);function change($str){    $name = array('1'=>'apple', '2'=>'pear', '3'=>'banana', '4'=>'orange');        $tmp = '';    for($i=0,$len=strlen($str); $i<$len; $i++){        $tmp .= $name[substr($str, $i, 1)];    }    return $tmp;}

三种方法都好,不过还是第一种最简洁速度最快

都能用。。试试

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn