outputfilter.trimwhitespace.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * Smarty plugin
  4. * @package Smarty
  5. * @subpackage PluginsFilter
  6. */
  7. /**
  8. * Smarty trimwhitespace outputfilter plugin
  9. *
  10. * File: outputfilter.trimwhitespace.php<br>
  11. * Type: outputfilter<br>
  12. * Name: trimwhitespace<br>
  13. * Date: Jan 25, 2003<br>
  14. * Purpose: trim leading white space and blank lines from
  15. * template source after it gets interpreted, cleaning
  16. * up code and saving bandwidth. Does not affect
  17. * <<PRE>></PRE> and <SCRIPT></SCRIPT> blocks.<br>
  18. * Install: Drop into the plugin directory, call
  19. * <code>$smarty->load_filter('output','trimwhitespace');</code>
  20. * from application.
  21. * @author Monte Ohrt <monte at ohrt dot com>
  22. * @author Contributions from Lars Noschinski <lars@usenet.noschinski.de>
  23. * @version 1.3
  24. * @param string $source input string
  25. * @param object &$smarty Smarty object
  26. * @return string filtered output
  27. */
  28. function smarty_outputfilter_trimwhitespace($source, $smarty)
  29. {
  30. // Pull out the script blocks
  31. preg_match_all("!<script[^>]*?>.*?</script>!is", $source, $match);
  32. $_script_blocks = $match[0];
  33. $source = preg_replace("!<script[^>]*?>.*?</script>!is",
  34. '@@@SMARTY:TRIM:SCRIPT@@@', $source);
  35. // Pull out the pre blocks
  36. preg_match_all("!<pre[^>]*?>.*?</pre>!is", $source, $match);
  37. $_pre_blocks = $match[0];
  38. $source = preg_replace("!<pre[^>]*?>.*?</pre>!is",
  39. '@@@SMARTY:TRIM:PRE@@@', $source);
  40. // Pull out the textarea blocks
  41. preg_match_all("!<textarea[^>]*?>.*?</textarea>!is", $source, $match);
  42. $_textarea_blocks = $match[0];
  43. $source = preg_replace("!<textarea[^>]*?>.*?</textarea>!is",
  44. '@@@SMARTY:TRIM:TEXTAREA@@@', $source);
  45. // remove all leading spaces, tabs and carriage returns NOT
  46. // preceeded by a php close tag.
  47. $source = trim(preg_replace('/((?<!\?>)\n)[\s]+/m', '\1', $source));
  48. // replace textarea blocks
  49. smarty_outputfilter_trimwhitespace_replace("@@@SMARTY:TRIM:TEXTAREA@@@",$_textarea_blocks, $source);
  50. // replace pre blocks
  51. smarty_outputfilter_trimwhitespace_replace("@@@SMARTY:TRIM:PRE@@@",$_pre_blocks, $source);
  52. // replace script blocks
  53. smarty_outputfilter_trimwhitespace_replace("@@@SMARTY:TRIM:SCRIPT@@@",$_script_blocks, $source);
  54. return $source;
  55. }
  56. function smarty_outputfilter_trimwhitespace_replace($search_str, $replace, &$subject) {
  57. $_len = strlen($search_str);
  58. $_pos = 0;
  59. for ($_i=0, $_count=count($replace); $_i<$_count; $_i++)
  60. if (($_pos=strpos($subject, $search_str, $_pos))!==false)
  61. $subject = substr_replace($subject, $replace[$_i], $_pos, $_len);
  62. else
  63. break;
  64. }
  65. ?>