Mahcih
Mahcih

Reputation: 23

Regular expression with PHP to replace newlines

I am trying to replace all the \n in a json string with a double pipe ||. Here is an example of a string :

{"comment":"test1
test2
test3"}';

Here is the regex I have done :

preg_match('/"comment":"(([^\n\t\r"]*)([\n\t\r]*))+"/', $a, $t);

The result of this preg_match is

Array
(
    [0] => "comment":"test1
test2
test3"
    [1] => 
    [2] => 
    [3] => 
)

I can't find what is wrong with my regexp.

Do I need a recursive pattern (?R) ?

Thanks.

Upvotes: 0

Views: 77

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174874

Use preg_replace function like below. I assumed that your input have balanced paranthesis.

preg_replace('~(?:"comment"[^\n]*|\G)\K\n([^{}\n]*)~', '||\1', $str)

DEMO

Upvotes: 1

vks
vks

Reputation: 67998

\n+(?=[^{]*})

You can simply use this.Replace with ||.

$re = "/\\n+(?=[^{]*})/i";
$str = "{\"comment\":\"test1\n test2\n test3\"}'";
$subst = "||";

$result = preg_replace($re, $subst, $str);

Upvotes: 0

Related Questions