Skip to content

Instantly share code, notes, and snippets.

@gskema
Last active August 4, 2018 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gskema/9e30ba912e1222be48d2cd8dbd0fc575 to your computer and use it in GitHub Desktop.
Save gskema/9e30ba912e1222be48d2cd8dbd0fc575 to your computer and use it in GitHub Desktop.
HTML whitespace trim RegEx (regular expression) for PHP. Useful for trimming HTML content before TCPDF processing.
<?php
// Trims whitespaces after any tags. Assumes that a tag ends with '/>', '\w>', '">'.
$html = preg_replace('#(["|\/|\w]>)(\s+)#', '$1', $html);
// Trims whitespaces before any tags. Assumes that tags start with '<\w+'
$html = preg_replace('#(\s+)(<\/?\w+)#', '$2', $html);
// Trims spaces between tags (both opening and closing).
// Assumes that a tag ends with '/>', '\w>', '">' and starts with '<\w+'
$html = preg_replace('#(["|\/|\w]>)(\s+)(<\/?\w+)#', '$1$3', $html);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment