0

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.

3
  • if you want to replace \n chars then why you use preg_match ? Commented Nov 26, 2014 at 11:42
  • Actually I don't want to replace all the newlines but only newlines in the comment. If you have a || just after {, the php function json_decode will encounter a problem. Commented Nov 26, 2014 at 11:47
  • 2
    @Hicham: cf my answer: decode the string, change the comment value, and encode the data again. It's the easiest and safest way to go Commented Nov 26, 2014 at 11:48

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

8 Comments

what does [^{}] represent ? Every caracter which is not { or } ?
yep, match all the chars except { or }
And if I want to replace it only in the content of the comment "comment":"HERE" I tried \n(?="comment":".*")
What's your expected output?
foo {"comment": "test1||test2||test3"}'; bar
|
0
\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);

2 Comments

Actually I don't want to replace all the newlines but only newlines in the comment. If you have a || just after {, the php function json_decode will encounter a problem.
@Hicham A newline is not allowed in a json value, they should all be replaced with \n. Then you can use json_decode() as said in the missing answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.