如果我有两个数组,即
$text = 'i am passed :)';
$fn = array(
':)',
':-)',
';;)'
)
$rep = array(
'smily1',
'smily2',
'smily3'
);
$output = str_replace($fn, $rep, $text);
echo $output;
我想为将来使用这个课程,我希望... 我怎么能为它上课......
以及我如何为此创建一个函数......
答案 0 :(得分:5)
基本上将您的函数包装在一个类中。如果您正在寻找更高级的功能,那么您必须指定。
<?php
class SmileyFilter {
private $_keys;
private $_values;
function add($key, $value) {
$this->_keys[] = $key;
$this->_values[] = $value;
}
function add_all($pairs) {
foreach ($pairs as $key => $value)
$this->add($key, $value);
}
function replace($text) {
return str_replace($this->_keys, $this->_values, $text);
}
}
// usage
$s = new SmileyFilter();
$s->add(':)', 'smily1');
$s->add(':-)', 'smily2');
$s->add(';;)', 'smily3');
/* OR
$smileys = array(
':)' => 'smily1',
':-)' => 'smily2',
';;)' => 'smily3');
$s->add_all($smileys);
*/
$s->replace('i am passed :)'); // "i am passed smily1"
?>
答案 1 :(得分:2)
class SmileyReplacer
{
protected static $_map = array(
':)' => 'smiley1',
':-)' => 'smiley2',
';;)' => 'smiley3'
);
public static function replace($string)
{
return str_replace(array_keys(self::$_map), self::$_map, $string);
}
}
// Usage
echo SmileyReplacer::replace('I am happy :)'); // I am happy smiley1
我认为没有理由为什么要实例化它,所以一个全静态类都没问题。其中没有真实的状态。你可以添加一个静态方法addMap(array $map)
,你可以传递一个关联数组,以防你想从外面提供地图。
如果您担心每次运行array_keys
时拨打replace
,请执行基准测试。我非常怀疑你能拿出足够的笑脸,所以它会对性能产生影响。
答案 2 :(得分:2)
<强>笑脸强>
class Smiley {
private $name;
private $data;
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
return $this;
}
public function getData() {
return $this->data;
}
public function setData($data) {
$this->data = $data;
return $this;
}
function __construct($name = null, $data = null) {
$this->name = $name;
$this->data = $data;
}
}
<强> SmileyMapper 强>
class SmileyMapper {
private $smilies = array();
public function addSmiley(Smiley $smiley) {
$this->smilies[] = $smiley;
return $this;
}
public function replaceSmileys($str) {
return str_replace(
array_map(
create_function(
'Smiley $item',
'return $item->getData();'
),
$this->smilies),
array_map(
create_function(
'Smiley $item',
'return $item->getName();'
),
$this->smilies),
$str
);
}
}
示例
$text = 'i am passed :)';
$fn = array(
':)',
':-)',
';;)'
);
$rep = array(
'smily1',
'smily2',
'smily3'
);
$sm = new SmileyMapper();
foreach ($fn as $k => $v) {
$sm->addSmiley(new Smiley($rep[$k],$v));
}
echo $sm->replaceSmileys($text);