Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating an array class with php

Tags:

php

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...

like image 543
Web Worm Avatar asked Dec 30 '22 06:12

Web Worm


1 Answers

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"
?>
like image 82
meagar Avatar answered Jan 09 '23 10:01

meagar