2

I want to be able to replace the middle parts of a string with an asterisk character. Is there any way I can do it in twig?

For example;

If I have

afashaisakiye@gmail.com

I want to return

afa********@gmail.com

If I have

+256 700033333

I want to return

+2567********33
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
iamafasha
  • 848
  • 10
  • 29

2 Answers2

1

You can extend twig with any PHP logic you want, e.g.

use Slim\Views\Twig;
use Slim\Views\TwigExtension;


$container['view'] = function ($container){
    $twig = new Twig(__DIR__.'/../resources/views');

    $twig->addFilter(new Twig_SimpleFilter('obfuscate', function($value, $char = '*', $visible = 4) {
        if ($visible % 2 != 0) $visible++;
        if (strlen($value) <= $visible) return str_repeat($char, strlen($value));
        return substr($value, 0, floor($visible) / 2).str_repeat($char, strlen($value) - $visible).substr($value, -1 * (floor($visible) / 2));
    }),

    return $twig;
};

{{ 'john.doe@gmail.com' | obfuscate }} {# output: jo**************om  #}
{{ 'john.doe@gmail.com' | obfuscate('-', 10) }} {# output: john.--------l.com   #}
{{ '123456' | obfuscate }} {# output: 12**56  #}
{{ '123' | obfuscate }} {# output: *** #}
{{ '1' | obfuscate }} {# output: * #}
{{ '+32497123456' | obfuscate }} {# output: +3********56 #}
DarkBee
  • 16,592
  • 6
  • 46
  • 58
-1

Try this code :

$email = 'afashaisakiye@gmail.com';
$test = explode('@', $email);
echo str_pad(substr($test[0], 0, 3),strlen($test[0]),"*").'@'.$test[1];

$number = '+256 700033333';
$number = str_replace(' ', '', $number);
echo str_pad(substr($number, 0, 5),strlen($number)-3,"*").substr($number, -3);
Jaydip kharvad
  • 1,064
  • 7
  • 13