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

时间:2018-02-21 13:37:15

标签: php replace str-replace

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

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

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


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

4 个答案:

答案 0 :(得分:7)

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

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

您还可以使用preg_quote使用preg_replace_callback()保护此内容:

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

编辑:以下代码是另一种方法,它使用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 ;

答案 1 :(得分:3)

另一种方法:

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

答案 2 :(得分:2)

你可以试试这个:

$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

这是你在找什么?

答案 3 :(得分:1)

你可以这样......

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