我正在努力使 php 正则表达式工作。
在 javascript 中执行正则表达式:
场景 1:javascript 正则表达式
在 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 正则表达式的结果数组
$year = $matches[0][0];
我尝试了很多组合来测试数组中的所有项目,例如
$year = $matches[x][0];
或
$year = $matches[0][x];
但无法检索到我在场景 1 中的 javascript 正则表达式中轻松获得的确切 4 位数(年份)预期结果。
预先感谢您的帮助
最佳答案
尝试在正则表达式前后添加 /
:
$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);
关于javascript - php 正则表达式不工作,返回主题字符串而不是正则表达式结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40558376/