Current Location: Home> Latest Articles> Practical Methods to Replace Phone Numbers in Documents Using PHP

Practical Methods to Replace Phone Numbers in Documents Using PHP

gitbox 2025-07-26

Common Methods to Replace Phone Numbers in Documents Using PHP

PHP is a widely-used web development language with powerful text processing capabilities that make it easy to replace phone numbers within documents. Below are several common and practical methods.

String Replacement Function

The built-in PHP function str_replace() is the simplest and most direct way to replace specified phone numbers with other characters quickly.

Example Code:


$text = "My phone number is: 1234567890";
$newText = str_replace('1234567890', '**********', $text);
echo $newText;

In this example, the string "1234567890" is replaced by ten asterisks, resulting in the output: "My phone number is: **********".

Regular Expression Replacement

For cases where phone number formats vary or multiple different numbers exist, using regular expressions with the preg_replace() function allows more flexible matching and replacement of phone numbers that follow a pattern.

Example Code:


$text = "My phone number is: 1234567890, contact number: 0987654321";
$pattern = '/\b\d{10}\b/';
$replacement = '**********';
$newText = preg_replace($pattern, $replacement, $text);
echo $newText;

The regex \b\d{10}\b matches 10-digit phone numbers, resulting in: "My phone number is: **********, contact number: **********" after replacement.

Iterating Through Document for Replacement

When needing to replace multiple phone numbers in a document and ensuring each is replaced accurately, first use preg_match_all() to find all matches, then replace each one individually.

Example Code:


$document = "Document content...";
$pattern = '/\b\d{10}\b/';
$replacement = '**********';
preg_match_all($pattern, $document, $matches);
foreach ($matches[0] as $match) {
    $document = str_replace($match, $replacement, $document);
}
echo $document;

This approach finds all phone numbers matching the pattern and replaces each one with asterisks, ensuring thorough processing of the document.

Summary

This article introduced three common PHP methods to replace phone numbers: direct string replacement, regex replacement, and iterative replacement. The choice depends on the specific scenario and complexity of phone number formats.

When using regex, adjust the pattern to fit the needs to ensure accurate matching. Also, be mindful of maintaining the document's format to avoid disruption during replacement.

Mastering PHP string handling techniques can greatly improve efficiency in text data processing and help develop safer, more effective applications.