用星号替换单词(精确长度)

Replace word with stars (exact length)

我正在尝试替换字符串中的单词,但我想获取在函数中找到的单词并将其替换为带星号且长度准确的单词?

这是可能的还是我需要以其他方式做到这一点?

$text = "Hello world, its 2018";
$words = ['world', 'its'];


echo str_replace($words, str_repeat("*", count(FOUND) ), $text);

您可以使用正则表达式来做到这一点:

$text = preg_replace_callback('~(?:'.implode('|',$words).')~i', function($matches){
    return str_repeat('*', strlen($matches[0]));
}, $text);
echo $text ; // "Hello *****, *** 2018"

您也可以在使用 preg_replace_callback() 之前使用 preg_quote 保护它:

 $words = array_map('preg_quote', $words);

编辑: 下面的代码是另一种方式,它使用 foreach() 循环,但可以防止不需要的行为(替换部分单词),并允许 multi-bytes 个字符:

$words = ['foo', 'bar', 'bôz', 'notfound'];
$text = "Bar&foo; bAr notfoo, bôzo bôz :Bar! (foo), notFOO and NotBar or 'bar' foo";
$expt = "***&***; *** notfoo, bôzo *** :***! (***), notFOO and NotBar or '***' ***";

foreach ($words as $word) {
    $text = preg_replace_callback("~\b$word\b~i", function($matches) use ($word) {
        return str_ireplace($word, str_repeat('*', mb_strlen($word)), $matches[0]);
    }, $text);
}

echo $text, PHP_EOL, $expt ;

你可以试试这个:

$text = "Hello world, its 2018";
$words = ['world', 'its'];

// Loop through your word array
foreach ($words as $word) {
    $length = strlen($word);                    // length of the word you want to replace
    $star   = str_repeat("*", $length);         // I build the new string ****
    $text   = str_replace($word, $star, $text); // I replace the $word by the new string
}

echo $text; // Hello *****, *** 2018

是您要找的吗?

另一种方法:

$text = "Hello world, its 2018";
$words = ['world', 'its'];

$f = function($value) { return str_repeat("*", strlen($value)) ; } ;
$replacement = array_map($f, $words);
echo str_replace($words, $replacement, $text);

你可以这样走..

$text = "Hello crazy world, its 2018";
$words = ['world', 'its'];

array_walk($words,"replace_me");

function replace_me($value,$key)
{
    global $text;
    $text = str_replace($value,str_repeat("*",strlen($value)),$text);
}

echo $text;