Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. <?php
  2. /**
  3. * @param string
  4. * @param string
  5. * @param string
  6. * @return string
  7. */
  8. function removeElementsByClass($html, $class, $tag_name='*')
  9. {
  10. if (stripos($html, '<html') === false)
  11. return $html;
  12.  
  13. foreach (['tag_name', 'class'] as $arg) {
  14. if (!is_string($$arg) || empty($$arg))
  15. throw new InvalidArgumentException("Expected non-empty string \$$arg");
  16. }
  17.  
  18. $doc = new DOMDocument('1.0', 'utf-8');
  19. $doc->loadHTML($html);
  20.  
  21. $xpath = new DOMXPath($doc);
  22. $query = sprintf('//%s[contains(attribute::class, "%s")]', $tag_name, $class);
  23. foreach($xpath->query($query) as $e)
  24. $e->parentNode->removeChild($e);
  25.  
  26. return $doc->saveHTML($doc->documentElement);
  27. }
  28.  
  29. /**
  30. * WordPress example: remove all elements with class `remove-for-mobile`
  31. * if user agent is considered mobile.
  32. */
  33. if (!is_admin() && wp_is_mobile()) {
  34. add_action('after_setup_theme', function()
  35. {
  36. ob_start(function($output)
  37. {
  38. return removeElementsByClass($output, 'remove-for-mobile');
  39. });
  40. }, 0);
  41. add_action('shutdown', 'ob_end_flush', PHP_INT_MAX);
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement