簡體   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