Replacing specific characters from a matched string in PHP regular expression where we don't know the number of instances of the match?

In PHP, you can use preg_replace() with regular expressions to replace specific characters from matched strings, even when you don't know how many instances exist. This is particularly useful for parsing delimited data where certain delimiters need conditional replacement.

Problem Example

Let's say we have this input string where we want to replace the pipe character "|" only when it appears between two numbers −

FirstName|John |LastName|Smith|SalaryProvided|2000|5000

The expected output should replace the "|" between 2000 and 5000 with a space −

FirstName|John |LastName|Smith|SalaryProvided|2000 5000

Solution Using preg_replace()

The following example demonstrates how to achieve this using a regular expression with lookahead and backreferences −

<?php
$SQLDatabaseResult = "FirstName|John |LastName|Smith|SalaryProvided|2000|5000";
$output = preg_replace("/(\d{4})\|(?=\d{4})/", "$1 ", $SQLDatabaseResult);
echo "The result is=" . "<br>";
echo $output;
?>

Output

This will produce the following output −

The result is=
FirstName|John |LastName|Smith|SalaryProvided|2000 5000

How the Regular Expression Works

The pattern /(\d{4})\|(?=\d{4})/ breaks down as follows −

  • (\d{4}) − Captures exactly 4 digits in group $1
  • \| − Matches the literal pipe character
  • (?=\d{4}) − Positive lookahead ensuring 4 digits follow

The replacement "$1 " keeps the captured digits and replaces the pipe with a space. The lookahead ensures we only match pipes between numbers without consuming the following digits.

Conclusion

Using preg_replace() with regular expressions provides a powerful way to conditionally replace characters based on context. The combination of capture groups and lookahead assertions allows precise pattern matching regardless of the number of occurrences.

Updated on: 2026-03-15T09:33:36+05:30

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements