Kylie
Kylie

Reputation: 11749

PHP return a string after a string, within a string

Lets say I have a string. (looks like JSON but actually a string, and no, I cant convert it to JSON)

     "heresSome":"data", "moreData":"and some more data", "theDataIwant:["THE DATA I WANT", "AND MORE DATA", "DUNNO HOW LONG", "BUT IT ENDS IN A BRACKET"], "moredata";

I want to just retrieve...

   "THE DATA I WANT", "AND MORE DATA", "DUNNO HOW LONG", "BUT IT ENDS IN A BRACKET"

from that above string.

Anybody know of some PHP magic to do that?

Ive done this...and it works. On a very small string such as the above.

$d = explode("theDataIwant:[", $string);
$d2 = explode("]", $d[1]);
var_dump($d2[0]); // returns THE DATA I WANT...etc

But the actual string I'm working with is huge, so this crashes when I try to run it. Maybe because got tons of weird white space and html tags as well? I'm not sure.

I'm sure this is a job for regex, but I'm not a regex master :(

Upvotes: 1

Views: 61

Answers (1)

namgold
namgold

Reputation: 1070

Try using regex:

$str = '"heresSome":"data", "moreData":"and some more data", "theDataIwant:["THE DATA I WANT, AND MORE DATA, DUNNO HOW LONG, BUT IT ENDS IN A BRACKET"], "moredata"';
$re = '/"theDataIwant:\["([^"]+)"/m';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
echo($matches[0][1]);

Upvotes: 3

Related Questions