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? Quote 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; } Quote 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
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.