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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.