【问题标题】:php regex not working, returning subject string instead of regex resultphp正则表达式不起作用,返回主题字符串而不是正则表达式结果
【发布时间】:2017-03-26 07:08:45
【问题描述】:

我正在努力使 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 正则表达式的文档,例如 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 位数(年份)预期结果。

提前感谢您的帮助

【问题讨论】:

  • 正则表达式分隔符。和print_r() 看看 $matches 包含什么。
  • 正则表达式分隔符是什么意思?你的意思是用 print_r 替换 echo ?

标签: javascript php json regex xpath


【解决方案1】:

尝试在您的正则表达式前后添加/

$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 === 1会更好。
  • 谢谢我试过了,结果很奇怪,这行得通: $yearNode = $xpath->query($yearXpath, $node)[0]; $year = $yearNode->nodeValue; $yearMatches = preg_match("/^[0-9][0-9][0-9][0-9]$/", $year, $matches);
    这里我不尝试访问结果,所以我得到了预期的原始字符串,但是如果我添加: $year = $matches[0];然后我得到一个 json parse ajax 失败
  • 我认为问题出在 $year = $matches[0];我不知道如何使用正则表达式的结果
【解决方案2】:

好吧,这可能是语义上的,但这行得通

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

(删除了 ^ 和 $,因为 4 位数字在字符串中)

谢谢!

【讨论】:

    猜你喜欢
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2014-12-21
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    相关资源
    最近更新 更多