Php preg_match不与模式一起工作
我试图用PHP搜索html标记,但似乎无法获得正确的正则表达式,我不确定我做错了什么。 以下是我试图搜索的模式:Php preg_match不与模式一起工作,php,regex,Php,Regex,我试图用PHP搜索html标记,但似乎无法获得正确的正则表达式,我不确定我做错了什么。 以下是我试图搜索的模式: <cas:serviceResponse xmlns:cas='somesite.edu'> <cas:authenticationSuccess> <cas:user>user29</cas:user> </cas:authenticationSuccess> </cas:serviceResponse>
<cas:serviceResponse xmlns:cas='somesite.edu'>
<cas:authenticationSuccess>
<cas:user>user29</cas:user>
</cas:authenticationSuccess>
</cas:serviceResponse>
用户29
我使用了$resp=htmlentities(file_get_contents($url));如果我回显$resp,上面的内容就会打印出来。
我试图使用preg_match在cas:user中搜索以提取用户名user29
下面是我尝试使用的正则表达式模式:
preg_match("'<cas:user>(.*?)</cas:user>'", $resp, $match);
preg_match(“(*?”)$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=您不应该尝试使用正则表达式解析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=您正在使用regex解析xml,这不是最好的选择。但是,如果必须使用正则表达式,请尝试以下操作:
preg_match("/<cas:user>(.*?)<\/cas:user>/", $resp, $match);
preg_match(“/(.*?/”,$resp,$match);
编辑
如果代码正常,请尝试echo$match[1]代码>。多亏了@Barmar.您使用正则表达式解析XML,这不是最好的选择。但是,如果必须使用正则表达式,请尝试以下操作:
preg_match("/<cas:user>(.*?)<\/cas:user>/", $resp, $match);
preg_match(“/(.*?/”,$resp,$match);
编辑
如果代码正常,请尝试echo$match[1]代码>。感谢@Barmar.(如果问题是关于Python的,我会说第一个参数有引号和撇号是可疑的。但据我所知,可能这就是php的工作原理,所以我什么也不说。)你的代码对我来说是有效的。请看这里:$match
是一个数组,所以echo$match代码>不起作用。使用print\u r()
或var\u dump()
(如果问题是关于Python的,我会说第一个参数有引号和撇号是可疑的。但据我所知,可能这就是php的工作原理,所以我什么也不说。)您的代码对我来说是有效的。请参见这里:$match
是一个数组,所以echo$match代码>不起作用。使用print\u r()
或var\u dump()
。在regexp周围需要分隔符。事实上,他使用的引号被用作分隔符。他的代码行得通。你说得对,现在编辑:)再编辑一次:你说得对。没有尝试过,但它确实有效。echo$match[1]代码>可能是他真正想要的。我也尝试过$match[1],但它不起作用。将编辑我的问题您需要在regexp周围使用分隔符。事实上,他使用的引号被用作分隔符。他的代码行得通。你说得对,现在编辑:)再编辑一次:你说得对。没有尝试过,但它确实有效。echo$match[1]代码>可能是他真正想要的。我也尝试过$match[1],但它不起作用。将编辑我的问题