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

PHPServer Side ProgrammingProgramming

For this, use preg_replace() in PHP. You need to also use Regular Expressions. Let’s say the following is our input −

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

The expected output is as follows wherein we have replaced a specific character “|” with a whitespace. This character was placed between two numbers 2000 and 5000 −

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


The PHP code is as follows

 Live Demo

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


This will produce the following output 

The result is=
FirstName|John |LastName|Smith|SalaryProvided|2000 5000
Updated on 13-Oct-2020 07:16:27