Thiago Yoithi
Thiago Yoithi

Reputation: 505

PHP: Extract using regex, preg_match() function

I want to extract the numbers 3 and 2 using preg_match()

[{"id":"3","value":"2"}]

These numbers won't be the same every time, it'll be generated depending on witch page the user is viewing.

Upvotes: 0

Views: 247

Answers (2)

pdvries
pdvries

Reputation: 1382

The code you are trying to extract is JSON. If you want to use preg_match, you can use Ωmega-'s solution (which I corrected a small bit '/'-slashes we're not included):

$str = '[{"id":"3","value":"2"}]';
preg_match('/(\d+)\D+(\d+)/', $str, $json_object);
$id = $json_object[1];
$value = $json_object[2];
echo $id;
echo $value;

If parsing JSON is what you're after:

$string = '{"id":"3","value":"2"}';
$json_dec = json_decode($string, true);
$id = $json_dec['id'];
$value = $json_dec['value'];
echo $id;
echo $value;

Hope this helps.

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 72971

The data appears to be JSON. As such, do not use Regular Expressions, use json_decode().

print_r(json_decode($yourdata, true));

Upvotes: 2

Related Questions