rocksfrow Posted July 31, 2008 Share Posted July 31, 2008 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 More sharing options...
effigy Posted August 4, 2008 Share Posted August 4, 2008 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 https://forums.phpfreaks.com/topic/117560-regex-get-html-tag-attribute-value/#findComment-607531 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.