繁体   English   中英

preg_match无法与模式一起使用

[英]preg_match not functioning with pattern

我正在尝试使用PHP搜索html标记,但似乎无法正确显示正则表达式,我不确定自己做错了什么。 这是我尝试搜索的模式:

<cas:serviceResponse xmlns:cas='somesite.edu'>
<cas:authenticationSuccess>
<cas:user>user29</cas:user>
</cas:authenticationSuccess>
</cas:serviceResponse>

我用$ resp = htmlentities(file_get_contents($ url)); 如果我回显$ resp,则上面的内容会打印出来。 我正在尝试使用preg_match在cas:user中搜索以提取用户名user29。

这是我要使用的正则表达式模式:

preg_match("'<cas:user>(.*?)</cas:user>'", $resp, $match);

但是,当我回显$ match [1]时,它似乎不起作用。 我究竟做错了什么?

您不应该尝试使用正则表达式解析XML。 而是使用DOM解析器,如下所示:

$xml = <<< XML
<?xml version="1.0"?>
<cas:serviceResponse xmlns:cas='somesite.edu'>
    <cas:authenticationSuccess>
        <cas:user>user29</cas:user>
    </cas:authenticationSuccess>
</cas:serviceResponse>
XML;

$dom = new DomDocument();
$dom->loadXML($xml);
$xpath = new DomXPath($dom);
$node = $xpath->query("//cas:user");
if ($node->length) {
    echo $node[0]->textContent;
}

可以在平面XML文档中使用较少的代码来完成此操作,但是名称空间会使事情复杂化,并使使用XPath更容易。

您正在使用regex解析XML,这不是最好的选择。 但是,如果必须使用正则表达式,请尝试以下操作:

preg_match("/<cas:user>(.*?)<\/cas:user>/", $resp, $match);

编辑

您的代码有效,请尝试echo $match[1]; 感谢@Barmar。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM