crazyghandi crazyghandi - 1 year ago 91
JSON Question

php regex not working, returning subject string instead of regex result

i'm struggling to make a php regex work.

doing the regex in javascript works:

scenario 1 : javascript regex

in php:
I get the node value through xpath:

$yearNode = $xpath->query(".//h2/a", $node)[0];
$year = $yearNode->nodeValue;

i add it to the json ajax response:

$responseStr[$i]['year'] = $year;

I regex the response in javascript:

var year = results[j]['year'].match("[0-9][0-9][0-9][0-9]");

this works fine but if I try in php:

scenario 2 : php

$yearNode = $xpath->query(".//h2/a", $node)[0];
$yearMatches = preg_match("[0-9][0-9][0-9][0-9]", $yearNode, $matches);
$year = $matches[0][0];
$responseStr[$i]['year'] = $year;

then try to get the result in javascript:

var year = results[j]['year'];

I get the whole subject string instead of the regex match, which is the equivalent of the php json response in scenario 1, ie

$yearNode = $xpath->query(".//h2/a", $node)[0];

what is wrong ? I've read some docs on php regex like but can't make it work

I think I'm probably misinterpreting the result array of the php regex

$year = $matches[0][0];

I've tried many combinations to test all the items inside the array like

$year = $matches[x][0];


$year = $matches[0][x];

but cannot retrieve the exact 4 digit (year) expected result that I easily get in the javascript regex in scenario 1.

thanks in advance for your help

Answer Source

Try to add / before and after your Regex:

$yearMatches = preg_match("/[0-9][0-9][0-9][0-9]/", $yearNode, $matches);

Preferably, add the start ^ and end $ boundaries:

$yearMatches = preg_match("/^[0-9][0-9][0-9][0-9]$/", $yearNode, $matches);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download