PHP – use a regular expression to extract a URL from XML attribute

I was working on an API response, which provided data in a custom XML markup within the string, which was returned. I wanted to simply extract the “linkTerm”. The snippet I got looked like this:

<link 
linkTarget="URL" 
linkTerm="https://some.provider.com/lib/something/detail.action?docID=5176530" 
linkWindow="_blank">Online-Zugang</link>

Now surely there will be more elegant ways of doing it, but I felt that I wouldn’t be guaranteed good valid links all the time and what I would get back from the API wasn’t just that custom XML, but a string, which contained the XML. All of this makes it more interested and I decided to simple look for the linkTerm attribute and use PHP’s preg_match() against it.

function makeURL($data){
	$data = htmlspecialchars_decode($data);
	$pattern = '/linkTerm="([^"]*)/';
	preg_match($pattern, $data, $matches);

	return $matches[1];
}

To be fair that function is a bit rubbish, as it doesn’t test the output, but like every nasty hack, this one will likey hang around for quite a while 😉

PHP – use a regular expression to extract a URL from XML attribute
Scroll to top