Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace all occurrences of a character except the first one in PHP using a regular expression?

Given an address stored as a single string with newlines delimiting its components like:

1 Street\nCity\nST\n12345

The goal would be to replace all newline characters except the first one with spaces in order to present it like:

1 Street
City ST 12345

I have tried methods like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[$street, $rest] = explode("\n", $input, 2);
$output = "$street\n" . preg_replace('/\n+/', ' ', $rest);

I have been trying to achieve the same result using a one liner with a regular expression, but could not figure out how.

>Solution :

You could use a regex trick here by reversing the string, and then replacing every occurrence of \n provided that we can lookahead and find at least one other \n:

$input = "1 Street\nCity\nST\n12345";
$output = strrev(preg_replace("/(?=.*\n)\n/", " ", strrev($input)));
echo $output;

This prints:

1 Street
City ST 12345
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading