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

Zor*_*ric 0 php replace str-replace

我试图替换字符串中的单词但是我想在函数中找到单词并将其替换为带有确切长度的星号的单词?

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

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


echo str_replace($words, str_repeat("*", count(FOUND) ), $text);
Run Code Online (Sandbox Code Playgroud)

Sys*_*all 7

您可以使用正则表达式来执行此操作:

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

你也可以使用preg_quote之前使用preg_replace_callback():

 $words = array_map('preg_quote', $words);
Run Code Online (Sandbox Code Playgroud)

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

$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 ;
Run Code Online (Sandbox Code Playgroud)