Reputation: 2066
if i have two arrays i.e
$text = 'i am passed :)';
$fn = array(
':)',
':-)',
';;)'
)
$rep = array(
'smily1',
'smily2',
'smily3'
);
$output = str_replace($fn, $rep, $text);
echo $output;
i want to make a class for this to use in future where i will want... how can i make a class for it...
and also how can i create a function for this...
Upvotes: 4
Views: 3931
Reputation: 10210
Smiley
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
);
}
}
Example
$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);
Upvotes: 2
Reputation: 317177
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
I see no reason why this should be instantiated, so an all static class is fine. There is no real state in it. You could add a static method addMap(array $map)
which you could pass an associate array in case you want to feed the map from outside.
If you are concerned about the calls to array_keys
each time you run replace
, do benchmark. I highly doubt you can come up with enough smileys so it would really have an impact on performance.
Upvotes: 3
Reputation: 239521
Basically by wrapping your function in a class. If you're looking for more advanced functionality then that, you'll have to specify.
<?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"
?>
Upvotes: 5