简体   繁体   中英

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.

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

\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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM