1

I have a multi-line string that I'm trying to extract, but it is not returning any pieces.

$input = '<script>
buffy = 1;
vampire = {
response: [{"sleep":"night"}]
};
</script>';

preg_match( '~response:(.*?)};~', $input, $output );

print_r( $output );

I am trying to extract [{"sleep":"night"}]

Kermit
  • 33,827
  • 13
  • 85
  • 121
  • Either that, or [this one](https://stackoverflow.com/a/45981809). Use the `s` modifier: [`(?s)response:\s*\K.*?(?=\s*};)`](https://regex101.com/r/o9EuIY/1). – InSync Aug 07 '23 at 01:30
  • Try [`response\s*:\s*\K((?:\[(?1)\]|\{(?1)\}|[^][{}]*?)*)`](https://regex101.com/r/L3wW2C/1) – Hao Wu Aug 07 '23 at 07:10
  • `.` Matches any character other than newline (or including line terminators with the /s flag) . So you need to replace `.*?` with `[\s\S]*?` – Oliver Hao Aug 07 '23 at 08:22

2 Answers2

2

check this out :

$input = '<script>
buffy = 1;
vampire = {
response: [{"sleep":"night"}]
};
</script>';

preg_match('/response:\s*([^;]+);/', $input, $output);

print_r($output[1]);
Freeman
  • 9,464
  • 7
  • 35
  • 58
0
'~response: (\[\{[^}]+}])~'

response    interpret as text
:           interpret as text
            interpret as text (one space)
(           start of capturing group
\[          interpret as text
\{          interpret as text
[^}]        anything up to the next }
+           ... and do this one or more times
}           interpret as text
]           interpret as text
)           end of capturing group
lukas.j
  • 6,453
  • 2
  • 5
  • 24