fork download
  1. <?php
  2.  
  3. $re = '~^id\h+"(.*)"(?:\Rid_p\h+"(.*)")?(?:\Rstr(?:\[\d])?\h*"")+$~m';
  4. $str = "id \"text 1\"\nstr \"\"\n\nid \"text 2\"\nstr \"\"\n\nid \"text 3\"\nstr \"\"\n\nid \"text 4\"\nstr \"\"\n\nid \"text 5\"\nstr \"\"\n\nid \"text 6\"\nid_p \"text 6-2\"\nstr[0] \"\"\nstr[1] \"\"";
  5. $result = preg_replace_callback($re, function($m){
  6. $loc = $m[0];
  7. if (isset($m[2])) {
  8. $loc = str_replace('str[1] ""','str[1] "' . $m[2] . '"', $loc);
  9. }
  10. return preg_replace('~^(str(?:\[0])?\h+)""~m', "$1\"$m[1]\"",$loc);
  11. }, $str);
  12.  
  13. echo $result;
Success #stdin #stdout 0s 52488KB
stdin
Standard input is empty
stdout
id "text 1"
str "text 1"

id "text 2"
str "text 2"

id "text 3"
str "text 3"

id "text 4"
str "text 4"

id "text 5"
str "text 5"

id "text 6"
id_p "text 6-2"
str[0] "text 6"
str[1] "text 6-2"