我有以下代码,我认为它应该可以工作,因为REGEX正确(在Ruby下运行并在regex101.com上检查):
if (preg_match('/<Approved>/', $response)) {
preg_match('/<Approved>(.*)<\/Approved>/', $response, $matches);
$app_code = $matches[0];
}
但我明白了:
PHP Warning: preg_match(): Unknown modifier '('
并且应该返回APPROVED
的匹配项不匹配。
搜索到的数据是XML,如:
<Approved>APPROVED</Approved>
或
<Approved>DECLINED</Approved>
编辑:
根据要求提供更多代码:
curl_close($ch);
var_dump($response);
if (preg_match('/<Approved>(.*)<\/Approved>/', $response)) {
preg_match('/<Approved>(.*)<\/Approved>/', $response, $matches);
$app_code = $matches[0];
}
if (preg_match('<ReturnCode>(.*)<\/ReturnCode>', $response)) { // This is the problem line
preg_match('/<ReturnCode>(.*)<\/ReturnCode>/', $response, $matches);
$retcode = $matches[0];
}
答案 0 :(得分:0)
抱歉,我的不好......我忘了把分隔符放在一条线上...... 代码应该是:
curl_close($ch);
var_dump($response);
if (preg_match('/<Approved>(.*)<\/Approved>/', $response)) {
preg_match('/<Approved>(.*)<\/Approved>/', $response, $matches);
$app_code = $matches[1];
}
if (preg_match('/<ReturnCode>(.*)<\/ReturnCode>/', $response)) { // This was the problem lines, forgot the delimiters
preg_match('/<ReturnCode>(.*)<\/ReturnCode>/', $response, $matches);
$retcode = $matches[1];
}
然后工作。
无论如何,用户@Simba评论的更好的方法是在这里使用内置的PHP XML解析器:
<?php
$myXMLData =
'<?xml version="1.0" encoding="UTF-8"?>
<Result>
<Approved>APPROVED</Approved>
<ReturnCode>N:APPROVED</ReturnCode>
</Result>';
$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object");
$approved = $xml->Approved;
echo $approved . "\n";
?>
输出:
APPROVED
所以我上面的小片最好是:
if (preg_match('/Approved/', $response)) {
$xml=simplexml_load_string($response) or die("XML Parse Error: Cannot create object");
$app_code = $xml->Approved;
$retcode = $xml->ReturnCode;
}