Search code examples
phpreplacestr-replace

Replace word with stars (exact length)


am trying to replace a word in a string BUT i want to get the word found in the function and replace it with a word with stars with the exact length ?

Is this possible or do i need to do this in some other way ?

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


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

Solution

  • You could use a regular expression to do that :

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

    You also could secure this using preg_quote before to use preg_replace_callback() :

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

    EDIT : The following code is another way, that use a foreach() loop, but prevent unwanted behaviors (replacing part of words), and allows multi-bytes characters:

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