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


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

Example

The PHP code is as follows

 Live Demo

<!DOCTYPE html>
<html>
<body>
<?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;
?>
</body>
</html>

Output

This will produce the following output 

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

Updated on: 13-Oct-2020

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements