我正在努力使PHP正则表达式工作。
在javascript中执行正则表达式:
场景1:javascript regex
在php:我通过xpath获取节点值:
$yearNode = $xpath->query(".//h2/a", $node)[0];
$year = $yearNode->nodeValue;
我将它添加到json ajax响应中:
$responseStr[$i]['year'] = $year;
我在javascript中正则化响应:
var year = results[j]['year'].match("[0-9][0-9][0-9][0-9]");
可以正常工作,但如果我在php中尝试:
场景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;
然后尝试在javascript中获取结果:
var year = results[j]['year'];
我得到整个主题字符串而不是正则表达式匹配,这相当于场景1中的php json响应,即
$yearNode = $xpath->query(".//h2/a", $node)[0];
怎么了?我读过一些php regex文档,如http://php.net/manual/fr/function.preg-match.php,但不能使它工作
我想我可能误解了php regex的结果数组
$year = $matches[0][0];
我已经尝试了许多组合来测试数组内的所有项目,如
$year = $matches[x][0];
或
$year = $matches[0][x];
,但无法检索准确的4位数(年)预期结果,我很容易得到在场景1中的javascript正则表达式。
提前感谢您的帮助
尝试在Regex之前和之后添加/
:
$yearMatches = preg_match("/[0-9][0-9][0-9][0-9]/", $yearNode, $matches);
最好添加起始^
和结束$
边界:
$yearMatches = preg_match("/^[0-9][0-9][0-9][0-9]$/", $yearNode, $matches);
好吧,这可能是语义上的问题,但这行得通
$yearMatches = preg_match("/[0-9][0-9][0-9][0-9]/", $title, $matches);
$year = $matches[0];
(删除^和$,因为4位数字在字符串中)
谢谢!