- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
<!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
Advertisements