Skip to content

Instantly share code, notes, and snippets.

@vlucas
Created January 18, 2010 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlucas/280277 to your computer and use it in GitHub Desktop.
Save vlucas/280277 to your computer and use it in GitHub Desktop.
$tags = array('link', 'script');
$tag_pattern = '#<\s*T\s+(.*)\s*(?:/>|>(.*)</T>)#Ui';
$matches = array();
// first assembling all work. The idea is that, if sorted by descending
// location offset, we can selectively remove tags.
//
// We'll need that to conditionally handle tags (like jTemplate's
// <script type="text/html" that should remain)
foreach($tags as $tag){
$p = str_replace('T', preg_quote($tag), $tag_pattern);
if(preg_match_all($p, $content, $ms, PREG_OFFSET_CAPTURE)){
foreach($ms[1] as $i => $m)
$matches[] = array(
'type' => $tag,
'tag' => $ms[0][$i][0],
'attributes_string' => $m[0],
'attributes' => array()
);
}
}
// Parse attr="value" pairs
$tokens = array();
foreach($matches as $mi => $val) {
if(!empty($matches[$mi]['attributes_string'])) {
// Match all attributes (key="value")
$tagAttributes = array();
$matchedAttributes = array();
preg_match_all("/([^\s=]*)=\"([^\"]*)\"/", $matches[$mi]['attributes_string'], $matchedAttributes, PREG_SET_ORDER);
// Assemble tag attributes
foreach($matchedAttributes as $attr) {
$tagAttributes[$attr[1]] = $attr[2];
}
} else {
$tagAttributes = array();
}
$matches[$mi]['attributes'] = $tagAttributes;
}
dump($matches)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment