SoFunction
Updated on 2025-03-02

How to replace sensitive text content with asterisks

In PHP, replacing sensitive text with an asterisk usually involves searching and replacing strings. You can use PHP's built-in functionsstr_replace()To implement this function. Here is a basic example of how to replace a specific sensitive word with an asterisk:

<?php
// Original text to be checked$text = "This text contains sensitive words such as violence and pornography.";
// Sensitive word array$sensitiveWords = ['Violence', 'pornography'];
// Replace sensitive words as asterisk$replacedText = str_replace($sensitiveWords, str_repeat('*', strlen($sensitiveWords[0])), $text);
echo $replacedText;
?>

In this example, we first define an array containing sensitive words$sensitiveWords. Then, we usestr_replace()Functions replace these sensitive words with asterisk strings of the same length.str_repeat('*')Functions are used to generate a string composed of asterisks with the same length as the replaced sensitive word.

If sensitive words can appear anywhere in the text and there may be multiple variations, you may need a more complex function to handle all cases. For example, you can use regular expressions withpreg_replace()Functions to match and replace sensitive words:

<?php
// Original text to be checked$text = "This text contains sensitive words, such as violence and pornography.";
// Sensitive word array$sensitiveWords = ['violence', 'pornography'];
// Create a regular expression pattern to match all sensitive words$pattern = '/' . implode('|', array_map('preg_quote', $sensitiveWords)) . '/i';
// Use regular expression to replace sensitive words with asterisk$replacedText = preg_replace($pattern, str_repeat('*', max(array_map('strlen', $sensitiveWords))), $text);
echo $replacedText;
?>

In this example, we usepreg_quote()Functions escape sensitive words to ensure they are processed correctly in regular expressions.implode()andarray_map()Functions are used to create a regular expression pattern that can match any sensitive words in an array.max()Functions are used to determine the length of the longest sensitive word so that the corresponding number of asterisks are used when replacing.

Note that this approach may need to be adjusted to your specific needs, for example, if your sensitive words list is very long, or if sensitive words appear in the text in a very diverse form, you may need a more complex algorithm to ensure that all sensitive words are replaced correctly.

This is the article about how PHP replaces sensitive text content with asterisks. For more relevant PHP sensitive content with asterisks, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!