Jump to content

regex get html tag attribute value


rocksfrow

Recommended Posts

function getAttribute($attrib, $tag){
  //get attribute from html tag
  $re = '/'.$attrib.'=["\']?([^"\' ]*)["\' ]/is';
  preg_match($re, $tag, $match);
  if($match){
    return urldecode($match[1]);
  }else {
    return false;
  }
}

$tag = '<tag attrib="blah" attrib2=blah attrib3=\'blah\'>';

echo getAttribute('attrib', $tag) . "\n";
echo getAttribute('attrib2', $tag) , "\n";
echo getAttribute('attrib3', $tag);

 

RESULT:

 

blah

blah

blah

 

The results are perfectly what I expected. I'm planning to use this function on enterprise level and am posting to see if anybody can spot anything wrong with this function?

Link to comment
https://forums.phpfreaks.com/topic/117560-regex-get-html-tag-attribute-value/
Share on other sites

It's OK for the most part, but I would:

 

  • Make the attribute name PREG safe.
  • Move the function into the if.
  • Make the pattern a little more exact.
  • Remove the useless else.

 

function getAttribute($attrib, $tag){
	//get attribute from html tag
	$re = '/' . preg_quote($attrib) . '=([\'"])?((?(1).+?|[^\s>]+))(?(1)\1)/is';
	if (preg_match($re, $tag, $match)) {
		return urldecode($match[2]);
	}
	return false;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.