the_crouton
the_crouton

Reputation: 53

preg_match not functioning with pattern

I am trying to search through html tags with PHP and I cannot seem to get the regex correct, I am not sure what I am doing wrong. Here is the pattern I am trying to search through:

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

I used $resp = htmlentities(file_get_contents($url)); and the above prints out if I echo $resp. I am trying to use preg_match to search in cas:user to extract the username , user29.

Here is the regex pattern I am trying to use:

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

But it doesn't seem to work when I echo $match[1]. What am I doing wrong?

Upvotes: 0

Views: 69

Answers (2)

ALFA
ALFA

Reputation: 1744

You're parsing XML with regex which is not the best option. However if you MUST use regular expressions try this:

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

EDIT

You code works, try echo $match[1];. Thanks to @Barmar.

Upvotes: 1

miken32
miken32

Reputation: 42683

You shouldn't try parsing XML with regular expressions. Instead use a DOM parser like so:

$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;
}

This could be done with less code in a flat XML document, but namespaces complicate things a bit and make it easier to use XPath.

Upvotes: 1

Related Questions