有没有办法可以替换树枝中的部分字符串?

Is there a way I can replace part of a string in twig?

我希望能够用星号字符替换字符串的中间部分。有什么办法可以用树枝做吗?

例如;

如果我有

afashaisakiye@gmail.com

我要return

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

如果我有

+256 700033333

我要return

+2567********33

试试这个代码:

$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);

您可以使用您想要的任何 PHP 逻辑来扩展 twig,例如

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 #}