D4V1D
D4V1D

Reputation: 5849

Replace third character from a 4-digit string with another in Twig

My goal is to mask one digit from a 4-digit string. Instead of having 2451, I'd like to have 24*1.

I tried {{ my_var|replace(slice(2, 1): '*') }} but this raises the following error: The function "slice" does not exist in My:Bundle:file.html.twig.

The weirdest thing being that {{ my_var|slice(2, 1) }} works perfectly. So the function does exists.

How can I do what I want to achieve?

Many thanks.

Upvotes: 0

Views: 784

Answers (3)

Khaled Attia
Khaled Attia

Reputation: 111

It's an old question, but I was looking for a Twig filter to hide x number of charts, and I ended up writing the following Twig extension.

<?php

declare(strict_types=1);

namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class AppExtension extends AbstractExtension
{
    public function getFilters(): array
    {
        return [
            new TwigFilter('mask', [$this, 'mask']),
        ];
    }

    /**
     * Find & Replace characters in a string for masking & hiding.
     */
    public function mask(string $string, $position = 0, int $charactersToMask = 4, $replacement = '*')
    {
        // Find & Replace ${charactersToMask} charts after first ${position} letter with ${replacement} in a string
        if (\strlen($string) >= ($charactersToMask + $position)) {
            return substr_replace($string, str_repeat($replacement, $charactersToMask), $position, $charactersToMask);
        }

        return $string;
    }
}

Usage:

{{ '+201001010111'|mask(4, 4, '*') }}

Output:

+201****10111

Upvotes: 0

Alexandru Olaru
Alexandru Olaru

Reputation: 7112

slice is a filter not a function, you can try to pipe them but in your case i do not see something achievable without creating your custom twig function or filter to mask your needs:

Upvotes: 1

Warzyw
Warzyw

Reputation: 339

Create Your own Twig extension - filter: SymfonyCookbook IMHO it would be cleanest way to do this.

Upvotes: 1

Related Questions