Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * @param string
- * @param string
- * @param string
- * @return string
- */
- function removeElementsByClass($html, $class, $tag_name='*')
- {
- if (stripos($html, '<html') === false)
- return $html;
- foreach (['tag_name', 'class'] as $arg) {
- if (!is_string($$arg) || empty($$arg))
- throw new InvalidArgumentException("Expected non-empty string \$$arg");
- }
- $doc = new DOMDocument('1.0', 'utf-8');
- $doc->loadHTML($html);
- $xpath = new DOMXPath($doc);
- $query = sprintf('//%s[contains(attribute::class, "%s")]', $tag_name, $class);
- foreach($xpath->query($query) as $e)
- $e->parentNode->removeChild($e);
- return $doc->saveHTML($doc->documentElement);
- }
- /**
- * WordPress example: remove all elements with class `remove-for-mobile`
- * if user agent is considered mobile.
- */
- if (!is_admin() && wp_is_mobile()) {
- add_action('after_setup_theme', function()
- {
- ob_start(function($output)
- {
- return removeElementsByClass($output, 'remove-for-mobile');
- });
- }, 0);
- add_action('shutdown', 'ob_end_flush', PHP_INT_MAX);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement