Skip to content

Instantly share code, notes, and snippets.

@pensiero
Created April 26, 2014 17:36
Show Gist options
  • Save pensiero/11326179 to your computer and use it in GitHub Desktop.
Save pensiero/11326179 to your computer and use it in GitHub Desktop.
// strip table tag
$doc = new \DOMDocument();
$doc->loadHTML($text);
$xpath = new \DOMXPath($doc);
foreach ($xpath->query('//table') as $node) {
$node->parentNode->removeChild($node);
}
$textWithoutTable = $doc->saveHTML();
// controlla che ci siano almeno X paragrafi
$count = count(explode("</p>", $textWithoutTable));
if ($count > $insertAfter) {
$regex = <<<'regex'
~
# let's define something
(?(DEFINE)
(?P<table> # To match nested table tags
<table\b[^>]*>
(?:
(?!</?table\b[^>]*>).
|
(?&table)
)*
</table\s*>
)
(?P<paragraph> # To match nested p tags
<p\b[^>]*>
(?:
(?!</?p\b[^>]*>).
|
(?&paragraph)
)*
</p\s*>
)
)
(?&table)(*SKIP)(*FAIL) # Let's skip table tags
|
(?&paragraph) # And match p tags
~xsi
regex;
$output = preg_replace_callback($regex, function($m)use($insertAfter, $code){
static $counter = 0; # A counter
$counter++;
if ($counter === $insertAfter) { # Should I explain?
return $m[0] . $code;
} else {
return $m[0];
}
}, $text);
if (empty($output)) {
return $text . $code;
}
return $output;
}
else {
// se non ci sono abbastanza paragrafi inserisce il codice alla fine del testo
return $text . $code;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment