1

I have the following string:

$string = '
Test1,One line
Test2,"Two lines 

Hello"
Test3,One line
';

I want to trim new lines within double quotation marks. So the end results will be:

$string = '
Test1,One line
Test2,"Two lines Hello"
Test3,One line
';

What's the regex approach to this?

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

1 Answers1

0

The only possible way is to match all between double quotes and replace all linebreaks with an empty string inside the matches only using preg_replace_callback:

$string = '
Test1,One line
Test2,"Two lines 

Hello"
Test3,One line
';
echo preg_replace_callback('~"[^"]*"~', function($m) { 
    return preg_replace('~\R+~', '', $m[0]);
 }, $string);

See the PHP demo.

Output:

Test1,One line
Test2,"Two lines Hello"
Test3,One line
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563