Extending Volt: Functions


Dec '15

May '16

1

653

1

edited Dec '15
Dec '15
// Get this from config
$replacement = "*";

$volt->getCompiler()->addFunction('censor', function ($arguments) use ($replacement) {
    list($string, $badWords, ) = eval('return [' . $arguments . '];');

    if (empty($badWords)) {
        return "'{$string}'";
    }

    foreach ((array) $badWords as $key => $badWord) {
        $badWords[$key] = str_replace('\*', '\S*?', preg_quote((string) $badWord));
    }

    $regex = '/(' . join('|', $badWords) . ')/ui';

    if (mb_strlen($replacement) == 1) {
        $result = preg_replace_callback($regex, function($matches) use ($replacement) {
            return str_repeat($replacement, mb_strlen($matches[1]));
        }, $string);
    } else {
        $result = preg_replace($regex, $replacement, $string);
    }

    if (is_string($result)) {
        return "'{$result}'";
    }

    return "'{$string}'";
});
{{ censor("The income tax is a three letter word, but telemarketers are scum.", ['tax', 'scum']) }}

Result:

The income *** is a three letter word, but telemarketers are ****.

If $replacement is a word (Phalcon for examle):

{{ censor("Laravel the best framework", ['Laravel', 'Symfony', 'Kohana', 'Zend']) }}

Result:

Phalcon the best framework

naaness
128

Thanks so much, Excellent explication!!