用相同长度的星号替换文本,用 PHP 保留空格


Replacing text by stars same length preserving whitespace with PHP

>我收到以下请求:我想使用 PHP 将文本中的子字符串替换为相同长度的星号。子字符串用<protected>标记屏蔽。我已经为此找到了解决方案,但我想更进一步:算法应保留空格,例如空格或换行符。

我举个例子。输入:

This is an example for <protected>hidden text
that's not covering one
not two
but four whole lines!</protected> Wow!

预期成果:

This is an example for ****** **** 
****** *** ******** ***
*** ***
*** **** ***** ****** Wow!

到目前为止我得到了什么:

echo preg_replace_callback('/<protected>(.*)<'/protected>/is',
    function ($matches) {
        return str_repeat('*', strlen($matches[1]));
    }, $input);

给(当然):

This is an example for ***************************************************************** Wow!

你们知道如何做到这一点吗?不一定使用正则表达式。

您可以使用

'S(匹配除空格以外的任何内容):

echo preg_replace_callback('~<protected>(.*)</protected>~is',
  function ($m) { return preg_replace('/'S/', '*', $m[1]); }, $input);

输出:

This is an example for ****** ****
****** *** ******** ***
*** ***
*** **** ***** ****** Wow!

对于挑战:

$pattern = '~(?:'G(?!'A)(?<!</protected>)|<protected>)'S('s*)(?:</protected>)?~';
echo preg_replace($pattern, '*'1', $str);

但是在我看来,首先提取<protected>标签之间的内容的方法更好。

$newText = preg_replace_callback('/<protected>(.*)<'/protected>/is',
    function ($matches) {
        return str_repeat('*', strlen($matches[1]));
    }, $input);
$newText = str_replace(' ', '*', $newText);

http://php.net/manual/de/function.str-replace.php