preg_match not functioning with pattern

45
March 15, 2019, at 10:40 PM

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?

Answer 1

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.

Answer 2

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.

READ ALSO
PHP: Delete Array from 2D-Array

PHP: Delete Array from 2D-Array

I am uploading a CSV file/report with 10 columns but at the end of the CSV file there are a few lines that just give details about the report like

24
Remove id from url in htaccess

Remove id from url in htaccess

How do I remove the id from the url and pass it with GET?

59
I&#39;m trying to creat and store a file locally in my pc using any web programing language

I'm trying to creat and store a file locally in my pc using any web programing language

I'm trying to save a txt file in my pc locally with php, but not in the download folderI need to add in different folder

33
Grabbing userID and field upon user creation

Grabbing userID and field upon user creation

I currently have a function that simply creates a user record in the database

22